Cowboy Tech

iOS-HTTP通信

URL path

let httpPath = NSURL(string:"http://jikexueyuan.com" )
let httpRequest = NSURLRequest(URL: httpPath!)

打印HTML代码

字符串类型输出

do {
    let httpCode = try NSString(contentsOfURL: httpPath!, encoding: NSUTF8StringEncoding)
    print(httpCode)
}catch{
    print(error)
}

二进制类型输出

let data = NSData(contentsOfURL:httpPath!)
print(data!)

二进制转字符串输出

let data = NSData(contentsOfURL:httpPath!)
print(NSString(data:data!, encoding: NSUTF8StringEncoding))

同步请求

打印HTML代码

do{
    let data = try NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: httpPath!), returningResponse: nil)
    print(NSString(data:data, encoding: NSUTF8StringEncoding))
}catch{
}

打印HTTP header

var resp:NSURLResponse?

    do{
     try NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: httpPath!), returningResponse: &resp)
    }catch{
    }

    if let r = resp{
       print(r)
    }

异步请求

NSURLConnection.sendAsynchronousRequest(httpRequest, queue: NSOperationQueue()){
    (resp:NSURLResponse?, data:NSData?, error:NSError?) -> Void in

    print(NSString(data: data!, encoding: NSUTF8StringEncoding))

}

Get communication

let httpPath:NSURL? = NSURL(string:"http://localhost:8080/MyServer/Hello.jsp?name=\(self.tvInput.text)")       
let httpRequest:NSURLRequest = NSURLRequest(URL:httpPath!)

NSURLConnection.sendAsynchronousRequest(httpRequest, queue: NSOperationQueue()){
(resp:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
    dispatch_sync(dispatch_get_main_queue(), {
        self.tvOut.text = NSString(data: data!, encoding: NSUTF8StringEncoding)! as String
    })
}
  1. Get方式是将传输数据放在地址栏
  2. 改变UI界面需要在主线程执行
  3. 不能传输庞大的数据

Post communication

let httpUrl = NSURL(string: "http://localhost:8080/MyServer/hello.jsp")
let req = NSMutableURLRequest(URL:httpUrl!)
req.HTTPMethod = "POST"
req.HTTPBody = NSString(string:"name=\(tvInput.text)").dataUsingEncoding(NSUTF8StringEncoding)

NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue()){

    (resp:NSURLResponse?, data:NSData?, error:NSError?) -> Void in

    if let d = data {
        dispatch_sync(dispatch_get_main_queue(), {
            self.tvOut.text = NSString(data: d, encoding: NSUTF8StringEncoding)! as String
        })}
    }