我是斯威夫特的新手。我想验证一个用户。我用“Deployd”作为服务器。API的文档就是这样写的:
HTTP 若要对用户进行身份验证,请将带有用户名和密码属性的POST请求发送到/login。 帖子/用户/登录 {“用户名”:"johnsmith",“密码”:“密码”}
我正在使用Alamofire解析JSON数据。这是我的代码:
let user = "root"
let password = "root"
// this is a testing user i've created in deployd's dashboard.
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
Alamofire.request(.POST, "http://localhost:2406/users/login/\(user)/\(password)")
.authenticate(usingCredential: credential)
.response { request, response, _, error in
println(response)
}这是来自Xcode控制台的响应:
Optional(<NSHTTPURLResponse: 0x7fdd906dc3a0> { URL: http://localhost:2406/users/login/root/root } { status code: 400, headers {
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Thu, 06 Aug 2015 13:01:54 GMT";
"Transfer-Encoding" = Identity; } })我知道我这样做是完全错误的。
发布于 2015-08-06 14:21:56
您正在使用http身份验证(headers),但是server / api并不要求您这样做(它实际上说400 -糟糕的请求--因此应该会指出API的错误使用);
相反,您必须在请求体中提供参数,因为规范规定它应该是您要提供给服务器的。要做到这一点,可以使用允许您包含参数的不同的Alamofire方法:
let parameters = ("username" : user, "password" : password)
Alamofire.request(.POST, "http://localhost:2406/users/login", parameters: parameters)并从调用中完全删除.authentication :)
希望能帮上忙!
https://stackoverflow.com/questions/31856921
复制相似问题