ios - Swift 中的 PUT 请求 header

标签 ios swift http-headers

我正在尝试在 Swift 中设置 PUT 请求。

我在 Postman 中尝试了以下设置,它有效:

服务器:

io.adafruit.com/api/feeds/ID

标题:

x-aio-key : 52c11fca919d446ba958e43d98bdaba3 (it's not the actual key)

正文:

last_value : ON

这是我用 Swift 开发的代码,但我不知道如何发送 header :

let url = NSURL(string: "https://io.adafruit.com/api/feeds/ID")
        let request = NSMutableURLRequest(URL: url!)
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "x-aio-key") //Optional
         request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "52c11fca919d446ba958e43d98bdaba3")
        request.HTTPMethod = "PUT"
        let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)
        let data = "last_value=ON".dataUsingEncoding(NSUTF8StringEncoding)
        request.HTTPBody = data

        let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

            if error != nil {

                //handle error
            }
            else {

                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Parsed JSON: '\(jsonStr)'")
            } 
        }
        dataTask.resume()

最佳答案

我可以推荐的是使用 Alamofire:https://github.com/Alamofire/Alamofire

有了这个框架,创建服务器请求变得非常容易。您还可以轻松设置将应用于请求的自定义 header 。

关于ios - Swift 中的 PUT 请求 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37241097/

相关文章:

ios - UIGraphicsGetImageFromCurrentImageContext() 在 UITableViewCell 中返回空白图像

ios - Xcode 9 : Failed to render and update Autolayout status for 'VC' T. .s.framework:移动 'TextFieldEffects.framework' 所需的代码签名

iphone - CF字符串!在 swift 1.2 中不能转换为 String

angularjs - 从 Angular.js $http 请求中删除 header

HTTP 范围 header

ios - 将 NSArray 作为 AFNetworking 中的参数传递

ios - 无法为 Flutter 项目构建 ipa [CocoaPods 找不到 pod "GoogleAppMeasurement":] 的兼容版本

ios - UICollectionViewController 的布局所有权(self.collectionView.collectionViewLayout 与 self.collectionViewLayout)

swift - 我如何在 Swift 4 中使用 Realm?

ios - 在 Swift 中使用 Alamofire 时如何获取响应头?