背景,我正在做一个particle.io安装的快速项目,有两条腿。基本上这是个帖子请求。
我的问题是我可以得到CURL和HTTParty. (Like below) but withURLSession`的正确响应--响应是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;
})发布于 2017-04-14 20:21:22
在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-urlencoded和URLComponents将格式设置为
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`.https://stackoverflow.com/questions/43418225
复制相似问题