当前位置:编程学习 > wap >>

IOS成长之路-NSMutableURLRequest实现Post请求

[cpp]
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.。。  
//注意转换编码格式 

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.。。
//注意转换编码格式

 

补充:移动开发 , IOS ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,