Swift 4 URLsession with Authentication API Key

时间:2017-11-16 02:09:36

标签: swift rest api authentication shippo

我正在尝试在Swift中为POST发出Shippo REST API请求,但由于它需要API身份验证密钥,我无法弄清楚如何在URLSession中实现密钥Swift 4.正如Apple文档所说,我无法使用urlsession.shared方法。 cURL命令是:

curl https://api.goshippo.com/addresses/ \
 -H "Authorization: ShippoToken shippo_test_Token_Here" \
 -d name="Shawn Ippotle" \ -d company="Shippo" \
 -d street1="215 Clayton St." \
 -d street2="" \
 -d city="San Francisco" \
 -d state="CA" \
 -d zip=94117 \
 -d country="US" \
 -d phone="+1 555 341 9393" \
 -d email="shippotle@goshippo.com"\
 -d is_residential=True\
 -d metadata="Customer ID 123456"

2 个答案:

答案 0 :(得分:5)

这里使用的是Alamofire。我希望这有帮助。我测试了它,它的工作原理。

func mainRequest(){

    var headers: HTTPHeaders = [
        "content-type": "application/json"
    ]

    let credentials = "shippo_test_8dc780c66d5dae1c42868596c0b359ba89108df9"
    headers["Authorization"] = "ShippoToken \(credentials)"

    var parameters:Parameters = [String : Any]()

    parameters["name"] = "Shawn Ippotle"
    parameters["company"] = "Shippo"
    parameters["street1"] = "215 Clayton St."
    parameters["street2"] = ""
    parameters["city"] = "San Francisco"
    parameters["state"] = "CA"
    parameters["zip"] = "94117"
    parameters["phone"] = "+1 555 341 9393"
    parameters["country"] = "US"
    parameters["email"] = "shippotle@goshippo.com"
    parameters["is_residential"] = "True"
    parameters["metadata"] = "Customer ID 123456"

    let url = "https://api.goshippo.com/addresses"

    Alamofire.request(url, method: .post, parameters: parameters , encoding: JSONEncoding.default, headers: headers)
        .responseJSON { (response) in
            switch response.result {
            case .success(let value):
                let swiftyJson = JSON(value)
                print ("return as JSON using swiftyJson is: \(swiftyJson)")
            case .failure(let error):
                print ("error: \(error)")
            }

    }
}

答案 1 :(得分:4)

如下:

// preparing http request
let yourUrl = URL(string: "https://api.goshippo.com/addresses/")! // whatever is your url
let yourAuthorizationToken = "ShippoToken shippo_test_Token_Here" // whatever is your token
let yourPayload = Data() // whatever is your payload

var request = URLRequest(url:yourUrl)
request.httpMethod = "POST"
request.setValue(yourAuthorizationToken, forHTTPHeaderField: "Authorization")
request.httpBody = yourPayload

// executing the call
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
    // your stuff here
})
task.resume()