Error Domain=NSCocoaErrorDomain Code=3840 #484 error analysis

created at 07-12-2021 views: 49

description

AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    [manager GET:@"http://www.google.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);
    }];

In AFNetworking, the above code will output

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.}

reason

This is because AFNetworking treats the response result as json by default, (default manager.responseSerializer = [AFJSONResponseSerializer serializer]). Obviously, the google homepage we requested returns not a json text, but an html page, but AFNetworking does not I don't know, it firmly believes that the result of the request is a json text! Then it stubbornly parses it in the form of json, obviously there is no way to parse a webpage into a dictionary or an array, so the above error occurred.

However, we expect it to handle this situation correctly, rather than prompting an error.
At this time, you must tell AFNetworking: Don't treat this webpage as json!
Just add before sending the request: manager.responseSerializer = [AFHTTPResponseSerializer serializer]

solution

change the code to:

AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"http://www.google.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);
}];

In this way, the html source code of the homepage of google.com can be correctly scraped.

created at:07-12-2021
edited at: 07-12-2021: