简体   繁体   中英

AFNetworking: how to get the response string when failed?

I am using

- (AFHTTPRequestOperation *)GET:(NSString *)URLString
                 parameters:(id)parameters
                    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

to communicate with the server, and it works great.

But sometimes, there is an error on the server, and it's response is not in json format. My partner wants me to show the error string, but since it went to the failure block, I can hardly get the original response string.

Anyone can help?

You may log operation.responseString line in success and failure block both to get response string of server.

If webservice has some kind of error and provide invalid json or response then log [error description] in failure block.

For reference please check below code snippet.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:120];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
[manager POST:[[NSString stringWithFormat:@"%@",URL]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:parameters 
     success:^(AFHTTPRequestOperation *operation, id responseObject) 
     {
       NSLog(@"Response: %@", operation.responseString);  
     } 
     failure:^(AFHTTPRequestOperation *operation, NSError *error) 
     {
       NSLog(@"Error: %@ \n %@", operation.responseString,[error description]);
     }];

In the failure block, add these codes:

NSDictionary *userInfo = [error userInfo];
NSString *message = [userInfo objectForKey:@"message"];

I think message is what you need, you can use NSLog to reveal the info.

To take error code(response code) you can use [operation.response statusCode];

Error detail should be here

id responseObject = error.userInfo[kErrorResponseObjectKey];

Referanced from: http://www.splinter.com.au/2014/09/10/afnetworking-error-bodies/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM