AFNetworking 关于JSON text did not start with array or object and option to allow fragments not set 错误

AFNetworking 关于JSON text did not start with array or object and option to allow fragments not set 错误

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中 上述代码将会 输出

Error Domain=NSCocoaErrorDomain Code=3840"The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text didnot startwitharrayor objectandoptionto allow fragmentsnotset.) UserInfo=0x8ea19a0 {NSDebugDescription=JSON text didnot startwitharrayor objectandoptionto allow fragmentsnotset.}

这是因为 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) {NSLog(@"%@",error);

}];

这样,就可以正确地把baidu.com首页的html源码抓回来啦.

你可能感兴趣的:(AFNetworking 关于JSON text did not start with array or object and option to allow fragments not set 错误)