同步Post方式
1 // MARK: - 同步Post方式 2 func synchronousPost() 3 { 4 //创建NSURL对象 5 var url:NSURL! = NSURL(string: "http://m.weather.com.cn/data/101010100.html") 6 7 //创建请求对象 8 var request : NSMutableURLRequest = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10) 9 10 request.HTTPMethod = "POST"//设置请求方式为POST,默认为GET 11 12 var str:String = "type=focus-c";//设置参数 13 var data:NSData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)! 14 request.HTTPBody = data; 15 16 //响应对象 17 var response:NSURLResponse? 18 19 //错误对象 20 var error:NSError? 21 22 //发出请求 23 var received:NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) 24 25 if (error != nil) 26 { 27 println(error?.code) 28 println(error?.description) 29 }else 30 { 31 var jsonString = NSString(data: received!, encoding: NSUTF8StringEncoding) 32 33 println(jsonString) 34 } 35 }
时间: 2024-10-18 22:25:01