AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
[manager GET:@" http://www.baidu.com" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"%@",error);
}];
在AFNetworking中 上述代码将会 输出
[manager GET:@" http://www.baidu.com" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"%@",error);
}];
在AFNetworking中 上述代码将会 输出
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8ea19a0 {NSDebugDescription=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的形式去解析,显然没办法把一个网页解析成一个字典或者数组,所以产生了上述错误.
然而,我们期望它能够正确地处理这个情形,而不是提示一个错误.
这时候 你必须告诉AFNetworking:别把这个网页当json来处理!
只需要在发送请求前加入:manager.responseSerializer = [AFHTTPResponseSerializer serializer]
AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"http://www.baidu.com" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
} failure:^(NSURLSessionDataTask *task, NSError *error) {