最近在調(diào)試接口是遇到了Content-Type為application/x-www-form-urlencoded的網(wǎng)絡(luò)請求,本來想著用封裝好的AFN就可以實(shí)現(xiàn)了梅惯,結(jié)果總是request timeout己莺,十分無奈雕什,經(jīng)過和服務(wù)器小伙伴進(jìn)行一番調(diào)試杖刷,決定暫時(shí)放棄AFN,轉(zhuǎn)用系統(tǒng)的網(wǎng)絡(luò)請求方法飞盆,廢話不多說,直接上干貨
//url處理
NSString *url = @"www.baidu.com";
NSURL *Url = [NSURL URLWithString:url];
//參數(shù)拼接
NSMutableData *postBody=[NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"key1=%@&key2&……",value1,value2,……] dataUsingEncoding:NSUTF8StringEncoding]];
//創(chuàng)建請求
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:Url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:15.0f];
[request setHTTPMethod: @"POST"];
//設(shè)置Content-Type
[request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postBody];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//異步請求網(wǎng)絡(luò)
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//數(shù)據(jù)處理
NSString *results = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
//? ? ? ? NSLog(@"結(jié)果:%@",results);
NSDictionary *resultDic = [self dictionaryWithJsonString:results];
//? ? ? ? NSLog(@"結(jié)果:%@次乓,獲取的字典數(shù)據(jù) = %@",results,resultDic);
}];
好了吓歇,上面就是關(guān)鍵代碼,有空了研究下AFN的x-www-form-urlencoded實(shí)現(xiàn)票腰。