如何在 NSURLSession 中使用 PUT 方法向 HTTPBody 添加数据? [英] How to add data to HTTPBody with PUT method in NSURLSession?

查看:92
本文介绍了如何在 NSURLSession 中使用 PUT 方法向 HTTPBody 添加数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码.它适用于 POST,但不适用于 PUT.

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()

推荐答案

是的,我同意 dgatwood,我认为您缺少的主要内容是 Content-Type 标头.

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

我只是想弄清楚这一点,似乎 PUT 和 PATCH 对它们的内容类型很挑剔.在您的情况下,看起来您正在使用 JSON,因此您可能有一些这样的代码:

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.

这篇关于如何在 NSURLSession 中使用 PUT 方法向 HTTPBody 添加数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆