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