//
// ViewController.swift
// http请求
//
// Created by admin on 16/2/26.
// Copyright © 2016年 jin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.post()
}
func post()
{
let urlStr = "http://test.com/login.php"
// url中含有中文的话需要编码下
let url = NSURL(string: urlStr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
// 初始化可变请求,用以之后改变对象的属性
let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
request.HTTPMethod = "post"
// 设置post数据,为字符串格式
let postData = "username=张三&password=zhang"
// 设置请求的data,需要转换成二进制的数据类型
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (responce:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
if data != nil
{
let json:AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print(json)
}
}
}
func get()
{
let urlStr = "http://test.com/login.php?username=张三&password=zhang"
// url中含有中文的话需要编码下
let url = NSURL(string: urlStr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
let request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (responce:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
if data != nil
{
let json:AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print(json)
}
}
}
}