//1.构造URL NSURL *url = [NSURLURLWithString:@"http://localhost:8090"]; //2.构造Request NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url]; //(1)设置为POST请求 [request setHTTPMethod:@"POST"]; //(2)超时 [request setTimeoutInterval:60]; //(3)设置请求头 //[request setAllHTTPHeaderFields:nil]; //(4)设置请求体 NSString *bodyStr = @"id=test&pwd=test&cmd=1"; NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding]; //设置请求体 [request setHTTPBody:bodyData]; //3.构造Session NSURLSession *session = [NSURLSessionsharedSession]; //4.task NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"response URL: %@", response.URL); NSLog(@"response Content Length: %lld", response.expectedContentLength); NSLog(@"response Encoding Name: %@", response.textEncodingName); NSLog(@"response MIME Type: %@", response.MIMEType); NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); NSLog(@"response Content Data : %@", [[NSStringalloc] initWithData:data encoding:gbkEncoding]); NSHTTPURLResponse *responseHeader=(NSHTTPURLResponse*)response; NSLog(@"response Status Code : %ld", (long)responseHeader.statusCode); NSLog(@"response Header Data : %@", responseHeader.allHeaderFields); }]; //5.执行 [task resume];
输出:
2016-04-11 13:58:02.399 test[2614:146749] response URL: http://localhost:8090/ 2016-04-11 13:58:02.400 test[2614:146749] response Content Length: 22 2016-04-11 13:58:02.400 test[2614:146749] response Encoding Name: gbk 2016-04-11 13:58:02.400 test[2614:146749] response MIME Type: text/html 2016-04-11 13:58:02.401 test[2614:146749] response Content Data : success:帐号验证通过! 2016-04-11 13:58:02.401 test[2614:146749] response Status Code : 200 2016-04-11 13:58:02.401 test[2614:146749] response Header Data : { Connection = close; "Content-Language" = "zh-CN"; "Content-Length" = 22; "Content-Type" = "text/html; charset=gbk"; }