[swift]发送后数据 nsurlsession

标签: json Swift
发布时间: 2017/3/5 3:42:54
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

嗨我想复制以下的 curl 命令在 swift 使用 NSURLSession 在操场上。

卷曲-k-i-H"接受︰ 应用/json"-H"X 应用程序:"-X 发布-d ' 用户名 = & 密码 =' https://address.com/api/login

这里是我到目前为止。 我在苦苦挣扎是我不能确定如何发送 post 数据例如: ' 用户名 = & 密码 ='。 任何帮助将不胜感激。

在此先感谢。

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

解决方法 1:

正如弗朗西斯科说,你可以创建 NSMutableURLRequestHTTPBody 。但你也应该 %转义值为 username ,而更重要的是, password

因此,假设您正在创建这样的请求︰

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

let session = NSURLSession(configuration: config)

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

let request = NSMutableURLRequest(URL: url!)
request.encodeParameters(["username": username, "password": password])

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

    guard error == nil && data != nil else {
        print(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

    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode != 200 {
            print("statusCode != \(httpResponse.statusCode)")
        }
    }

    // since you set `Accept` to JSON, I'd assume you'd want to parse it:

    do {
        if let responseObject = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: AnyObject] {
            print(responseObject)
        }
    } catch {
        print(error)
        print(NSString(data: data!, encoding: NSUTF8StringEncoding))
    }
}

task.resume()

所以,问题是如何 encodeParameters 生成请求正文发一本词典。是的你想 %逃脱什么不在的毫无保留的字符集,但遗憾的是 stringByAddingPercentEscapesUsingEncoding 是不胜任这项工作。所以你像这样做︰

extension NSMutableURLRequest {

    /// Percent escape
    ///
    /// Percent escape in conformance with W3C HTML spec:
    ///
    /// See http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
    ///
    /// - parameter string:   The string to be percent escaped.
    /// - returns:            Returns percent-escaped string.

    private func percentEscapeString(string: String) -> String {
        let characterSet = NSCharacterSet(charactersInString: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._* ")

        return string
            .stringByAddingPercentEncodingWithAllowedCharacters(characterSet)!
            .stringByReplacingOccurrencesOfString(" ", withString: "+", options: [], range: nil)
    }

    /// Encode the parameters for `application/x-www-form-urlencoded` request
    ///
    /// - parameter parameters:   A dictionary of string values to be encoded in POST request

    func encodeParameters(parameters: [String : String]) {
        HTTPMethod = "POST"

        HTTPBody = parameters
            .map { "\(percentEscapeString($0))=\(percentEscapeString($1))" }
            .joinWithSeparator("&")
            .dataUsingEncoding(NSUTF8StringEncoding)
    }
}

此外,我一般使用更复杂, encodeParameters ,也接受数字、 布尔值,而日期类型,不想离题太远你的核心问题,如何向正确生成请求的两个字符串键/值对。

赞助商