How to read a simple string from a POST request in

2020-05-19 06:47发布

问题:

I'm using AFNetworking to communicate with a server through POST that responds with a simple string containing the information I need. I'm using the following code:

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST: MY_URL
   parameters: MY_PARAMETERS
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //do something
      }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //etc.
      }];

However, it seems that AFNetworking expects every response to be in JSON format because I get this error when I execute my request:

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=0x1566eb00 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

How can I tell AFNetworking that it's OK that the response is not a JSON object? I've seen something involving AFHTTPClient, but it doesn't seem to be part of AFNetworking anymore.

回答1:

You can tell the AFHTTPRequestOperationManager or AFHTTPSessionManager how to handle the response, e.g. before calling POST, you can do the following:

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

Then in your success block, you can convert the NSData to a string:

NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

Having said that, you might want to contemplate converting your web service to return JSON response, as it's far easier to parse that way (and differentiate between a valid response and some server error).



回答2:

  NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);

you can get response description details like below

 NSLog(@"JSON: %@", [responseObject description]);


回答3:

Much better way would be subclassing AFHTTPResponseSerializer and overriding there

func responseObject(for response: URLResponse?, data: Data?, error: NSErrorPointer) -> Any?

There you can parse response, cast to type you need and return.