Swift URLSession的行为与Curl或HTTParty不同

时间:2017-04-14 19:45:20

标签: swift curl httparty

背景 我正在开展一个快速的项目,particle.io设置了两条腿的auth部分。基本上这是一个POST请求。

我的问题是我可以通过CURLHTTParty. (Like below) but with URLSession获得正确的回复,回复是404。

通过 CURL

curl -X POST -u "abcd:secret" -d password=true -d email="wwsd@gmail.com" https://api.particle.io/v1/orgs/xxx/customers 

通过 HTTParty

require 'HTTParty'
def register_spark_two_legged_user(query)
   return HTTParty.post("https://api.particle.io/v1/orgs/xxx/customers", body: query, basic_auth:{"username":"abcd","password":"secret"}) 
end

query = {"email":"wwsd@gmail.com", "no_password":true}
json = register_spark_two_legged_user query
p json

我想在Swift中做到这一点:

func twoLegged() {
        let urlString = "https://api.particle.io/v1/orgs/xxx/customers"
        let parameters = ["email":"wwsd@gmail.com","no_password":true] as [String : Any]
        let userName = "abcd"
        let password = "secret"
        let loginString = userName+":"+password
        let loginData = loginString.data(using: String.Encoding.utf8)!
        let base64LoginString = loginData.base64EncodedString()

        let url = URL(string: urlString)!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
        do {
           request.httpBody = try JSONSerialization.data(withJSONObject:   parameters, options: .prettyPrinted)
        } catch let error {
           print(error.localizedDescription)
        }
        URLSession.shared.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
        if let e = error {
            print(e.localizedDescription)
        } else {
            let json = try? JSONSerialization.jsonObject(with: data!, options: [])
            debugPrint(response as Any)
            print(json)
        }
       }.resume()

我错过了什么吗?谢谢您的帮助。以下链接可能有用:community.particle.io

编辑我改变了httpBody仍然不起作用。

var comp = URLComponents()
        comp.queryItems = [
            URLQueryItem(name: "no_password", value: "true"),
            URLQueryItem(name: "email", value: "wwsd@gmail.com"),
        ]
        request.httpBody = comp.query?.data(using: String.Encoding.utf8)
        request.setValue("application/x-www-form-urlencode", forHTTPHeaderField: "Content-Type")

输出

Optional({
    error = "Not Found";
    ok = 0;
})

1 个答案:

答案 0 :(得分:0)

curl中,您要将数据发送为application/x-www-form-urlencoded,即以

格式发送
no_password=true&email=wwsd@gmail.com

但是在Swift中,你将数据作为JSON发送出去。

request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
# wrong: form data is expected, not JSON.

您可以使用application/x-www-form-urlencodedURLComponents格式化为URLQueryItem

var comp = URLComponents()
comp.queryItems = [
    URLQueryItem(name: "no_password", value: "true"),
    URLQueryItem(name: "email", value: "wwsd@gmail.com"),
]
request.httpBody = comp.query?.data(using: .utf8)

你也没有将请求传递给URLSession ......

URLSession.shared.dataTask(with: request) { ... }
//                               ^~~~~~~ you were passing `url`.