Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST request with AFNetworking 2.0 - AFHTTPSessionManager

Hej,

I am struggling with doing a POST request to the parse REST API. I am using AFNetworking 2.0. My code for the AFHTTPSessionManager Subclass looks as follows:

+ (ParseAPISession *)sharedSession {
     static ParseAPISession *sharedSession = nil;
     static dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
         sharedSession = [[ParseAPISession alloc] initWithBaseURL:[NSURL URLWithString:kSDFParseAPIBaseURLString]];
    });
   return sharedSession;
}

And:

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self) {
       [self.requestSerializer setValue:kSDFParseAPIApplicationId forHTTPHeaderField:@"X-Parse-Application-Id"];
       [self.requestSerializer setValue:kSDFParseAPIKey forHTTPHeaderField:@"X-Parse-REST-API-Key"];
   }

   return self;
}

I am doing the request like this:

[[ParseAPISession sharedSession] POST:@"ClassName" parameters: [NSDictionary dictionaryWithObjectsAndKeys:@"name", @"name", nil] 
                              success:^(NSURLSessionDataTask *task, id abc) {
                                  NSLog(@"%@", abc);
                              } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                  NSLog(@"%@", error);
}];

Doing this I always get this kind of error:

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

Since the GET Request works like a charm I am quite confused why I can’t POST something. Can anybody halp me with this problem?

Best regards!

UPDATE

Happily after testing around a lot this Error message isn't displayed anymore, unfortuatelly another appeared:

<NSHTTPURLResponse: 0x8b96d40>
{ URL: https://api.parse.com/1/users }
{ status code: 400, 
headers {
    "Access-Control-Allow-Origin" = "*";
    "Access-Control-Request-Method" = "*";
    "Cache-Control" = "no-cache";
    Connection = "keep-alive";
    "Content-Length" = 130;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Wed, 30 Oct 2013 20:01:58 GMT";
    Server = "nginx/1.4.2";
    "Set-Cookie" = "_parse_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlNjIxZjUxMzY3NWVhZWJmMDYyYWYwMGJiZTQ3MThmMWE%3D--851bd31b07e7dba2c5f83bb13a8d801ecbea42c4; domain=.parse.com; path=/; expires=Fri, 29-Nov-2013 20:01:58 GMT; secure; HttpOnly";
    Status = "400 Bad Request";
    "X-Runtime" = "0.060910";
    "X-UA-Compatible" = "IE=Edge,chrome=1";
} }

Can anyone tell me what the Status: 400 Bad Request is telling me and how I can get rid of it?

like image 769
RuNsTa Avatar asked Oct 30 '13 10:10

RuNsTa


2 Answers

This worked for me :

in the AFHTTPSessionManager subclass initialise it with the following serialisers:

[self setRequestSerializer:[AFHTTPRequestSerializer serializer]]; [self setResponseSerializer:[AFJSONResponseSerializer serializer]];

like image 21
Meseery Avatar answered Nov 09 '22 01:11

Meseery


This error means that your POST request went through, the server is successfully returning you some data, which NSJSONSerialization is having trouble parsing.

You probably need to set your AFJSONResponseSerializer to allow JSON fragments.

In the init method of your AFHTTPSessionManager subclass:

AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
[self setResponseSerializer:responseSerializer];

If this doesn't work, you probably have an encoding issue. From the NSJSONSerialization class reference:

The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.

Check the encoding type sent by your server.

Finally, you can either set breakpoints inside of AFNetworking, or set up AFNetworkActivityLogger, which will log requests as they are sent and received to your console. This tool is incredibly helpful for debugging this type of issue.

like image 129
Aaron Brager Avatar answered Nov 08 '22 23:11

Aaron Brager