Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableURLRequest body malformed after iOS 8.3 update

Before today's iOS 8.3 update I had my code working right, but after updating server started rejecting requests as it could not find JSON data.

I found that iOS is sending a wrong application/x-www-form-urlencoded text (not properly encoded as it seems a JSON object):

Wireshark screenshot showing wrong data

This is what I expected to be sent (and what was sent on 8.2): Wireshark screenshot showing expected object

As I said, this only happens on iOS 8.3 (I just tried on iOS simulator with 8.2 and it works).

I think the problem is in one of the classes that appear on these lines:

NSData *bodyData = [NSJSONSerialization dataWithJSONObject:requestDict options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPBody = bodyData;

I checked Apple documentation and none appears as modified recently.

Is someone suffering the same or knows what can lead to this?

Thanks.

like image 387
Bartomeu Galmés Avatar asked Apr 09 '15 01:04

Bartomeu Galmés


2 Answers

I also have encountered this problem in one application.

It looks like it could be a bug introduced in iOS 8.3. From the official Framework Reference, it is said of the NSURLSessionConfiguration's HTTPAdditionalHeaders property:

This property specifies additional headers that are added to all tasks within sessions based on this configuration. For example, you might set the User-Agent header so that it is automatically included in every request your app makes through sessions based on this configuration.

From what I understand, a Content-Type set in this configuration should be automatically included in every request made through this session, which is no longer the case since 8.3. I've filed a radar.

UPDATE: The radar has been set as 'duplicate' of another so it's more likely a bug.

As Luca pointed out, the work around is to set the Content-Type directly on the request:

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

Source: https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSessionConfiguration_class/#//apple_ref/occ/instp/NSURLSessionConfiguration/HTTPAdditionalHeaders

like image 141
Rufel Avatar answered Nov 06 '22 06:11

Rufel


I put the comment as answer here:

Try to indicate the http method like

[request setHTTPMethod:@"POST"]

and / or, the request length

[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

and / or the content type

[request setValue:@"application/<YOUR CONTENT TYPE>"forHTTPHeaderField:@"Content-Type"];
like image 7
Luca Iaco Avatar answered Nov 06 '22 05:11

Luca Iaco