URLSession 配置的标头设置仅适用于 PUT,不适用于 POST

bol*_*ovt 1 ios nsurlsession swift

我正在使用 NSURLSession 默认会话使用以下代码

  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())
  }
Run Code Online (Sandbox Code Playgroud)

但似乎 content-type: application/json 设置仅适用于 PUT 方法,这是服务器响应

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
Run Code Online (Sandbox Code Playgroud)

当我为每个 POST 请求添加标头设置时,它会再次起作用。

        req.addValue("application/json", forHTTPHeaderField: "Content-Type")
Run Code Online (Sandbox Code Playgroud)

服务器

POST application/json /api/v2/DevHiin 201 19.925 ms - 95
PUT application/json /api/v2/DevBoost 201 23.729 ms - 65
Run Code Online (Sandbox Code Playgroud)

但这确实不是一个漂亮的解决方案,而且整个代码真的很奇怪,有人有洞察力告诉我发生了什么事吗?

非常感谢!

Jus*_*ney 5

看起来 iOS 8.3 在 NSURLSessionConfiguration 中引入了一个错误,其中指定的 Content-Type 未被遵守(有关类似问题,请参阅iOS 8.3 更新后 NSMutableURLRequest body malformed )。这使我们的整个应用程序陷入瘫痪,直到我们实施了后端解决方法。我们还将 Content-Type 添加到每个可变 POST 请求中,就像您所描述的那样。

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
Run Code Online (Sandbox Code Playgroud)