Search code examples
iosjsonafnetworkingjsonserializer

Error Code -1011 with status code 401


I am using AFNetworking to post a username and password, so that I can get a JSON response. I am readily getting JSON response in POSTMAN client as in below snapshot : enter image description here

But then, whenever I hit the same URL with the AFNetworking library :

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

[manager POST:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

The error I get is as below : enter image description here

I even tried adding the below code, but it always gave the same error response :

AFHTTPRequestSerializer *serializerRequest = [AFHTTPRequestSerializer serializer];
[serializerRequest setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

manager.requestSerializer = serializerRequest;

manager.responseSerializer = [AFJSONResponseSerializer serializer];

How can I get the JSON response as in the postman client. Any kind of help is appreciated.


Solution

  • If the HTTP Response code 401 is not in your acceptableStatusCodes list. AFNetworking will not proceed to deserialise the object. But instead create an NSError object which is what you are seeing outputted.

    This functionality can be found AFURLResponseSerialization.m:132.

    If you would like to update the HTTP codes you wish to accept you can use:

    self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 200)];

    Otherwise if you are confident that the request contains JSON body, you can still access the data from the NSError that is produced as its contained in the userInfo with the key AFNetworkingOperationFailingURLResponseErrorKey and deserialise it manually.

    More information: https://github.com/AFNetworking/AFNetworking/issues/2410#issuecomment-63304245