Content-Type为x-www-form-urlencoded的POST请求

最近在调试接口是遇到了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实现。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容