最近在调试接口是遇到了Content-Type为application/x-www-form-urlencoded的网络请求,本来想着用封装好的AFN就可以实现了,结果总是request timeout,十分无奈,经过和服务器小伙伴进行一番调试,决定暂时放弃AFN,转用系统的网络请求方法,废话不多说,直接上干货
//url处理
NSString *url = @"www.baidu.com";
NSURL *Url = [NSURL URLWithString:url];
//参数拼接
NSMutableData *postBody=[NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"key1=%@&key2&……",value1,value2,……] dataUsingEncoding:NSUTF8StringEncoding]];
//创建请求
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:Url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:15.0f];
[request setHTTPMethod: @"POST"];
//设置Content-Type
[request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postBody];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//异步请求网络
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//数据处理
NSString *results = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
// NSLog(@"结果:%@",results);
NSDictionary *resultDic = [self dictionaryWithJsonString:results];
// NSLog(@"结果:%@,获取的字典数据 = %@",results,resultDic);
}];
好了,上面就是关键代码,有空了研究下AFN的x-www-form-urlencoded实现。
网友评论