您的位置:首页 > 产品设计 > UI/UE

NSMutableURLRequest实现Post请求

2015-12-24 20:43 429 查看
[cpp] view
plaincopy

NSData *bodyData = [[bodyString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]dataUsingEncoding:NSUTF8StringEncoding];//把bodyString转换为NSData数据

NSURL *serverUrl = [[NSURL URLWithString:RequestUrl] URLByAppendingPathComponent:urlStr];//获取到服务器的url地址

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverUrl

cachePolicy:NSURLRequestReloadIgnoringLocalCacheData

timeoutInterval:10];//请求这个地址, timeoutInterval:10 设置为10s超时:请求时间超过10s会被认为连接不上,连接超时

[request setHTTPMethod:@"POST"];//POST请求

[request setHTTPBody:bodyData];//body 数据

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];//请求头

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];//同步发送request,成功后会得到服务器返回的数据

//返回的数据 根据系统的不同会返回不同编码的数据,比如windows 为GBK,Ubuntu 为UTF8.。。

//注意转换编码格式

转自:http://blog.csdn.net/like7xiaoben/article/details/8735390
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: