PUT请求Swift中的Header

时间:2016-05-15 16:56:44

标签: 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中开发的代码,但我不知道如何发送标题:

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

3 个答案:

答案 0 :(得分:1)

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

使用此框架可以非常轻松地创建服务器请求。您还可以轻松设置将应用于请求的自定义标头。

答案 1 :(得分:0)

使用

request.setValue("52c11fca919d446ba958e43d98bdaba3", forHTTPHeaderField: "x-aio-key")

而不是

request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "x-aio-key") //Optional
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "52c11fca919d446ba958e43d98bdaba3")

答案 2 :(得分:0)

我在写请求期间看到你犯了一个错误。我大胆编辑如下:

示例请求:

Accept: */*
Accept-Encoding: gzip, deflate
Content-Type: application/json
x-aio-key: your-aio-key
Accept-Language: en-us

{
  "name": "your-new-feed-name"
}

夫特:

    let url = NSURL(string: "https://io.adafruit.com/api/feeds.json")
    let request = NSMutableURLRequest(URL: url!)
    request.timeoutInterval = 60

    request.setValue("your-aio-key-here", forHTTPHeaderField: "x-aio-key")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
    request.setValue("en-us", forHTTPHeaderField: "Accept-Language")

    request.HTTPMethod = "POST"
    let data = "{\"name\": \"test-post-new-feed\"}".dataUsingEncoding(NSUTF8StringEncoding)
    request.setValue("\(data!.length)", forHTTPHeaderField: "Content-Length")
    request.HTTPBody = data

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)


    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        dispatch_async(dispatch_get_main_queue(), {
            print("Response: \(response)")

            if ((error) != nil) {
                print(error)
            } else {
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Parsed JSON: '\(jsonStr)'")
            }
        })
    })
    task.resume()

响应:

HTTP/1.1 201 Created
Content-Type: application/json
Location: http://localhost:3002/api/feeds/22
Connection: close
Cache-Control: max-age=0, private, must-revalidate
Etag: "7215ee9c7d9dc229d2921a40e899ec5f"

解析JSON:

{
  "id":id-of-new-feed-post,
  "key":"test-post-new-feed",
  "name":"test-post-new-feed",
  "description":null,
  "history":true,
  "unit_type":null,
  "unit_symbol":null,
  "last_value":null,
  "status":"online",
  "visibility":"private",
  "enabled":true,
  "license":null,
  "created_at":"2016-05-16T03:44:41.402Z",
  "updated_at":"2016-05-16T03:44:45.404Z"
}

更多:

*** Data formats: json, form-encoded, csv

*** Required Fields: name - string, alphanumeric, unique per user.

*** Optional: description - text; unit_type - string; unit_symbol - string; visibility - {public, private}

*** Response Codes: 201: Successful, includes location header to the new feed.

结果: result image here - click to view