1

I'm working with NSURLSession default session with the following code

  var defaultSession : NSURLSession {
    var config = NSURLSessionConfiguration.defaultSessionConfiguration()
    config.HTTPAdditionalHeaders = [
      // FIXME: for POST this line doesn't work, but for PUT it works, this could be a bug.
      "Content-Type": "application/json"
    ]
    return NSURLSession(configuration: config, delegate: self.delegate, delegateQueue: NSOperationQueue.mainQueue())
  }

But seems like the content-type: application/json setting only works for the PUT method, here is the server resonse

POST application/x-www-form-urlencoded /api/v2/DevHiin 400 24.815 ms - 11
PUT application/json /api/v2/DevBoost 201 51.151 ms - 65

When I add the header setting for every POST request, it works again.

        req.addValue("application/json", forHTTPHeaderField: "Content-Type")

server

POST application/json /api/v2/DevHiin 201 19.925 ms - 95
PUT application/json /api/v2/DevBoost 201 23.729 ms - 65

But this is really not a beautiful solution and the code as a whole is really weird, does anybody have the insight to tell me what's going on?

Many thanks!

bolerovt
  • 623
  • 7
  • 18

1 Answers1

4

It looks like iOS 8.3 introduced a bug in NSURLSessionConfiguration whereby the specified Content-Type is not being honored (see NSMutableURLRequest body malformed after iOS 8.3 update for a similar issue). This brought our entire app to its knees until we implemented a back-end workaround. We also added the Content-Type to each mutable POST request, like you describe.

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
Community
  • 1
  • 1
Justin Whitney
  • 1,242
  • 11
  • 17
  • One gotcha with this, if you have another process which adds the Content-Type header to the same mutable request object, then using addValue will concatenate the header to something like "application/json,application/json". For that reason, it might be better form to use [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; This will add the header if it doesn't exist, or update it if it does. – Justin Whitney Apr 10 '15 at 17:40