How to add data to HTTPBody with PUT method in NSURLSession?

坚强是说给别人听的谎言 提交于 2019-12-11 13:29:06

问题


This is my code. It's working with POST but not with PUT.

let url:NSURL = NSURL(string: urlApi)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "PUT"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.addValue("a5f96d8c01000194c639d6b5f3b199eb", forHTTPHeaderField: "token")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let params:[String: AnyObject] = ["id" : 296,"name" : "asdad","space_width":10,"space_height":10,"space_altitude":10,"actions":""]
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())

let task = session.dataTaskWithRequest(request) {
    (
    let data, let response, let error) in

    guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
        print("error")
        return
    }

    let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    print(dataString)
}
task.resume()

回答1:


Yeah I agree with dgatwood, I think the main thing you're missing is the Content-Type header.

I was just trying to figure this out and it seems that PUT and PATCH are particular about their content type. In your case, looks like you're using JSON, so you might have some code like this:

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

You have that for the "Accept" header, but that controls something different. Give it a shot.



来源:https://stackoverflow.com/questions/36987497/how-to-add-data-to-httpbody-with-put-method-in-nsurlsession

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!