发送帖子数据nsurlsession [英] Sending post data nsurlsession

查看:52
本文介绍了发送帖子数据nsurlsession的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在操场上使用NSURLSession快速复制以下curl命令.

Hi i'm trying to replicate the following curl command in swift using NSURLSession in a playground.

curl -k -i -H接受:application/json" -H"X-Application:" -X POST -d'username =& password ='

curl -k -i -H "Accept: application/json" -H "X-Application: " -X POST -d 'username=&password=' https://address.com/api/login

这是我到目前为止所掌握的.我苦苦挣扎的地方是我不确定如何发送帖子数据,例如:'username =& password ='.任何帮助将不胜感激.

Here's what I've got so far. Where i'm struggling is that i'm unsure how to send the post data e.g.: 'username=&password='. Any help would be appreciated.

谢谢.

import Foundation
import XCPlayground

// Let asynchronous code run
XCPSetExecutionShouldContinueIndefinitely()



let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["Accept" : "application/json", "X-Application" : "<AppKey>"]


let session = NSURLSession(configuration: config)


var running = false
let url = NSURL(string: "https://address.com/api/login")
let task = session.dataTaskWithURL(url!) {
   (let data, let response, let error) in
   if let httpResponse = response as? NSHTTPURLResponse {
      let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
      println(dataString)
   }
   running = false
}

running = true
task.resume()

推荐答案

您可以创建可变的URLRequest并设置httpBody.但是您还应该对username,更重要的是,对password的值进行百分比转义.

You can create a mutable URLRequest and set the httpBody. But you should also percent escape the values for username and, more importantly, for password.

所以,想象一下您的请求是这样创建的:

So, imagine your request being created like so:

let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = ["Accept" : "application/json", "X-Application" : "<AppKey>", "Content-Type" : "application/x-www-form-urlencoded"]

let session = URLSession(configuration: config)

let url = URL(string: "https://identitysso.betfair.com/api/login")!

var request = URLRequest(url: url)
request.setBodyContent(["username": username, "password": password])

let task = session.dataTask(with: request) { data, response, error in
    // make sure there wasn't a fundamental networking error

    guard let data = data, let response = response as? HTTPURLResponse, error == nil else {
        print(error ?? "Unknown error")
        return
    }

    // if you're going to check for NSHTTPURLResponse, then do something useful
    // with it, e.g. see if server status code indicates that everything is OK

    guard 200 ..< 300 ~= response.statusCode else {
        print("statusCode not 2xx; was \(response.statusCode)")
        return
    }

    // since you set `Accept` to JSON, I'd assume you'd want to parse it;
    // In Swift 4 and later, use JSONDecoder; in Swift 3 use JSONSerialization

    do {
        if let responseObject = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject] {
            print(responseObject)
        }
    } catch let parseError {
        print(parseError)
        print(String(data: data, encoding: .utf8) ?? data as NSData)
    }
}

task.resume()

所以问题是setBodyContent如何在给定字典的情况下构建请求主体.是的,您想百分号转义非保留字符集中的任何内容,但可悲的是CharacterSet.urlQueryAllowed不能胜任.因此,您可能会执行以下操作:

So the question is how setBodyContent builds the request body given a dictionary. Yes, you want to percent-escape anything not in the unreserved character set, but sadly CharacterSet.urlQueryAllowed is not up to the job. So you might do something like:

extension URLRequest {

    /// Populate the HTTPBody of `application/x-www-form-urlencoded` request
    ///
    /// - parameter parameters:   A dictionary of keys and values to be added to the request

    mutating func setBodyContent(_ parameters: [String : String]) {
        let parameterArray = parameters.map { (key, value) -> String in
            let encodedKey   = key.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
            let encodedValue = value.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
            return "\(encodedKey)=\(encodedValue)"
        }
        httpBody = parameterArray
            .joined(separator: "&")
            .data(using: .utf8)
    }
}

extension CharacterSet {

    /// Character set containing characters allowed in query value as outlined in RFC 3986.
    ///
    /// RFC 3986 states that the following characters are "reserved" characters.
    ///
    /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
    /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
    ///
    /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
    /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
    /// should be percent-escaped in the query string.
    ///
    /// - parameter string: The string to be percent-escaped.
    ///
    /// - returns: The percent-escaped string.

    static let urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)

        return allowed
    }()

}

此外,我通常使用更复杂的setBodyContent,该setBodyContent也接受数字,布尔值和日期类型,但我不想偏离核心问题,即如何正确构建对两个字符串键的请求/值对.

Furthermore, I generally use a more complicated setBodyContent that also accepts numeric, boolean, and date types, but I didn't want to digress too far from your core question, how to properly build request for two string key/values pairs.

有关Swift 2再现,请参见此答案的先前版本.

For Swift 2 rendition, see previous revision of this answer.

这篇关于发送帖子数据nsurlsession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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