【发布时间】:2017-02-09 00:55:51
【问题描述】:
我是.net 开发人员,但对iOS 和swift 开发非常陌生,只需要使用Swift2 使用Web API 的帮助
Asp.net Web API 已使用OAuth2 身份验证构建,并已发布到安装了 SSL 证书的 Azure VM 服务器。 API 站点本身工作正常,通过 Postman 测试
但是,当我开始在 Swift 中编写前几行代码以获取身份验证令牌时,我遇到了困难。在阅读了一些在线教程后,我决定参与Alamofire,并制作了以下代码sn-p:
func GetToken() {
let params = [
"grant_type" : "password",
"username" : "123456@qq.com",
"password" : "averygoodpassword"
]
let headers = [
"Content-Type" : "application/x-www-form-urlencoded"
]
request(.POST, "https://api.example.com/token",
parameters: params,
headers: headers,
encoding: .JSON)
.responseJSON { request, response, result in
print (request)
print (response?.description)
print (result)
switch result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
case .Failure(let data, let error):
print("Request failed with error: \(error)")
if let data = data {
print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
}
}
}
}
它最终在Xcode 中得到以下输出,这似乎不太好。 error = unsupported_grant_type 告诉我请求已发送到服务器,但参数未与请求一起正确发送。我实在想不通原因和解决办法,在网上挖了几天,但仍然感到绝望。有人可以帮忙吗?即使有人可以在没有任何 3rd 方库的情况下提供纯粹的快速解决方案,也会非常有帮助。谢谢!
Xcode 输出:
可选({ 网址:https://api.example.com/token }) 可选(“ { URL:https://api.example.com/token } { 状态代码:400,标头 {\n \"Access-Control-Allow-Headers\" = \"Content-Type\";\n \"Access-Control-Allow-方法\" = \"GET、POST、PUT、DELETE、OPTIONS\";\n \"Access-Control-Allow-Origin\" = \"*\";\n \"Cache-Control\" = \" no-cache\";\n \"Content-Length\" = 34;\n \"Content-Type\" = \"application/json;charset=UTF-8\";\n Date = \"Fri, 2016 年 9 月 30 日 10:30:31 GMT\";\n 过期 = \"-1\";\n Pragma = \"no-cache\";\n 服务器 = \"Microsoft-IIS/8.5\";\ n \"X-Powered-By\" = \"ASP.NET\";\n} }") 成功 JSON 成功:{ 错误=“不支持的授权类型”; }
【问题讨论】: