【发布时间】:2017-02-27 19:26:12
【问题描述】:
我正在尝试使用 Swift 3 的 MS Translator API(现在在游乐场玩,但目标平台是 iOS)。但是,当我尝试获取 OAuth2 的访问令牌时,我被卡住了。我有以下代码(我试图从Obtaining an access token 的示例中移植代码):
let clientId = "id".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let clientSecret = "secret".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let scope = "http://api.microsofttranslator.com".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let translatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
let requestDetails = "grant_type=client_credentials&client_id=\(clientId)&client_secret=\(clientSecret)&scope=\(scope)"
let postData = requestDetails.data(using: .ascii)!
let postLength = postData.count
var request = URLRequest(url: URL(string: translatorAccessURI)!)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("\(postLength)", forHTTPHeaderField: "Content-Length")
request.httpBody = postData
URLSession.shared.dataTask(with: webRequest) { (returnedData, response, error) in
let data = String(data: returnedData!, encoding: .ascii)
print(data)
print("**************")
print(response)
print("**************")
print(error)
}.resume()
当然,我使用了有效的 clientId 和有效的 clientSecret。
现在回调打印以下信息。首先,returnedData 包含请求无效的消息,以及以下消息:
"ACS90004: The request is not properly formatted."
其次,响应带有 400 代码(这符合请求格式不正确的事实)。
三、错误为零。
现在我正在使用 Postman 测试调用,当我使用相同的 URI 并将 requestDetails 字符串作为原始正文消息(我手动添加 Content-Type 标头)时,我得到了相同的响应。但是,当我将 Postman UI 中的正文类型更改为 application/x-www-form-urlencoded 并通过其 UI 将请求详细信息作为键值对键入时,调用成功。现在看来,我在消息格式方面做错了,或者甚至是 Swift URLRequest/URLSession API 出现了问题,但是,我无法掌握什么。有人可以帮帮我吗?谢谢。
【问题讨论】:
标签: ios swift security web oauth-2.0