一.AFNetworking的簡(jiǎn)單使用:
導(dǎo)入頭文件
#import <AFNetworking.h>
//1.創(chuàng)建會(huì)話管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.封裝參數(shù)
NSDictionary *dict = @{
@"appid":@"201211268888",
@"type":@"ios"
};
//3.發(fā)送GET請(qǐng)求
/*
第一個(gè)參數(shù):請(qǐng)求路徑(NSString)+ 不需要加參數(shù)
第二個(gè)參數(shù):發(fā)送給服務(wù)器的參數(shù)數(shù)據(jù)
第三個(gè)參數(shù):progress 進(jìn)度回調(diào)
第四個(gè)參數(shù):success 成功之后的回調(diào)(此處的成功或者是失敗指的是整個(gè)請(qǐng)求)
task:請(qǐng)求任務(wù)
responseObject:注意!!!響應(yīng)體信息--->(json--->oc))
task.response: 響應(yīng)頭信息
第五個(gè)參數(shù):failure 失敗之后的回調(diào)
*/
[manager GET:@"http://..." parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"success--%@--%@",[responseObject class],responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"failure--%@",error);
}];
遇到type類型無(wú)法解析時(shí):進(jìn)入AFURLResponseSerialization.m文件227行左右添加上需要解析的類型:
- self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
+ self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
請(qǐng)求時(shí)可能遇到的錯(cuò)誤及解決方案:
1. error : JSON text did not start with array or object and option to allow fragments not set.
這是因?yàn)?AFNetworking默認(rèn)把響應(yīng)結(jié)果當(dāng)成json來(lái)處理,(默認(rèn)manager.responseSerializer = [AFJSONResponseSerializer serializer]) ,很顯然,我們請(qǐng)求的百度首頁(yè) 返回的并不是一個(gè)json文本,而是一個(gè)html網(wǎng)頁(yè),但是AFNetworking并不知道,它堅(jiān)信請(qǐng)求的結(jié)果就是一個(gè)json文本!然后固執(zhí)地以json的形式去解析,顯然沒(méi)辦法把一個(gè)網(wǎng)頁(yè)解析成一個(gè)字典或者數(shù)組,所以產(chǎn)生了上述錯(cuò)誤.解決這種問(wèn)題只需要在發(fā)送請(qǐng)求前加上:
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
但這樣的話可能會(huì)導(dǎo)致responseObject的輸出類型為_NSInlineData,輸入結(jié)果為這樣:
(lldb) po responseObject
<7b226365 6c6c7068 6f6e6522 3a6e756c 6c2c2275 73657270 7764223a 22222c22 61646472 65737322 3a6e756c 6c2c2269 64223a30 2c227573 65726e61 6d65223a 22777037 227d>
因此在請(qǐng)求成功后要對(duì)respon進(jìn)行一個(gè)data->json的轉(zhuǎn)換:
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(@"ResDic = %@",dic);
二.json轉(zhuǎn)字典
- (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
return responseJSON;
}