1.默认的响应的解析
1.1 AFN默认不支持接受text/html数据类型,只需要增加即可
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
1.2 AFN默认把所有获取的数据当做JSON来反序列化
1.2.1 如果使用AFN或取非JSON数据,一定要修改AFN默认的反序列化操作,让其返回原始的二进制,程序员可以根据数据具 体的格式自行反序列化
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
例:
- (void)loadHTMLData { // 极其少见
// 1.请求地址
NSString *URLString = @"http://www.baidu.com";
// 2.获取manager
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 2.1 增加AFN支持的文件类型
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
// 2.2 如果使用AFN或取非JSON数据,一定要修改AFN默认的反序列化操作,让其返回原始的二进制,程序员可以根据数据具体的格式自行反序列化
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@ %@",[responseObject class],html);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
正常情况:
- (void)loadJSONData {
// 1.请求地址
NSString *URLString = @"http://news.coolban.com/Api/Index/news_list/app/2/cat/0/limit/20/time/1457168894/type/0";
// 2.封装请求参数
NSMutableDictionary *parameters = [NSMutableDictionary new];
parameters[@"channel"] = @"appstore";
parameters[@"uuid"] = @"19C2BF6A-94F8-4503-8394-2DCD07C36A8F";
parameters[@"net"] = @"5";
parameters[@"model"] = @"iPhone";
parameters[@"ver"] = @"1.0.5";
// 3.获取manager,
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 3.1 增加AFN支持的文件类型
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
// 4.发送请求
[manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"%@ %@",[responseObject class],responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
2.默认的请求的解析
2.1 AFN默认只能向服务器发送普通的二进制,不支持发送JSON
2.1.1修改AFN默认的请求解析,让AFN支持发送JSON
manager.requestSerializer = [AFJSONRequestSerializer serializer];
例:
- (void)postJSON { // 很少见
// 1.请求地址
NSString *URLString = @"http://localhost/php/upload/postjson.php";
// 2.使用字典,封装要发送给服务器的JSON数据
NSDictionary *parameters = @{@"name":@“1111"};
// 3.获取网络会话
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 3.1 修改AFN默认的请求解析,让AFN支持发送JSON
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"%@ %@",[responseObject class],responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}