How to add data to HTTPBody with PUT method in NSU

2019-07-24 02:03发布

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条回答
We Are One
2楼-- · 2019-07-24 03:04

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.

查看更多
登录 后发表回答