POST: NSURLSession

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //http://api.izhangchu.com/
        //methodName=HomeIndex&user_id=0&version=1.0
        
        //NSURLSession实现POST请求
        //1.创建NSURL对象
        let url = NSURL(string: "http://api.izhangchu.com/")
        //2.创建NSMutableURLRequest对象
        let request = NSMutableURLRequest(URL: url!)
        
        //传递参数
        let paramString = "methodName=HomeIndex&user_id=0&version=1.0"
        let data = paramString.dataUsingEncoding(NSUTF8StringEncoding)
        
        request.HTTPBody = data
        
        //设置请求方式
        request.HTTPMethod = "POST"
        
        
        //POST请求除了设置请求体的参数之外,还可以修改请求头
        /*
        //1)设置参数的大小,默认是会传递
        //Content-Length
        let len = "\(data?.length)"
        request.setValue(len, forHTTPHeaderField: "Content-Length")
 
        
        //2)设置请求数据的格式
        //默认参数值是"application/x-www-form-urlencoded"
         //还有其他值"text/html"、"text/xml"等等
        //Content-Type
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
         */
        
        //3.NSURLSession
        let session = NSURLSession.sharedSession()
        //4.task
        let task = session.dataTaskWithRequest(request) { (data, response, error) in
            
            if let err = error {
                //下载失败
                print(err)
            }else{
                
                let httpRes = response as! NSHTTPURLResponse
                if httpRes.statusCode == 200 {
                    //下载成功
                    
                    let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    print(str)
                    
                }else{
                    print("下载失败")
                }
                
                
            }
            
        }
        //5.开始请求
        task.resume()
        
        
    }

你可能感兴趣的:(POST: NSURLSession)