我正在尝试使用 Swift 3 的 MS Translator API(现在在 Playground 玩,但目标平台是 iOS)。然而,当我尝试获取 OAuth2 的访问 token 时,我陷入了困境。我有以下代码(我尝试从 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。
现在回调打印以下信息。首先,返回的数据包含请求无效的消息以及以下消息:
"ACS90004: The request is not properly formatted."
其次,响应带有 400 代码(这符合请求格式不正确的事实)。
第三,错误为零。
现在我正在使用 Postman 测试调用,当我使用相同的 URI 并将 requestDetails 字符串作为原始正文消息时(我手动添加了 Content-Type
header ),我得到了同样的 react 。但是,当我将 Postman UI 中的正文类型更改为 application/x-www-form-urlencoded
并通过其 UI 以键值对形式输入请求详细信息时,调用成功。现在看来我在消息格式方面做错了,或者甚至可能是 Swift URLRequest/URLSession API 做错了,但是,我无法掌握到底是什么。有人可以帮我吗?谢谢。
最佳答案
好的,经过一些更绝望的谷歌搜索和实验,我发现了我的错误。为了子孙后代:
问题在于对 PUT http 请求正文中的参数进行编码。而不是:
let scope = "http://api.microsofttranslator.com"
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
我必须使用以下内容:
let scope = "http://api.microsofttranslator.com"
.addingPercentEncoding(withAllowedCharacters:
CharacterSet(charactersIn: ";/?:@&=$+{}<>,").inverted)!
似乎 API(或 HTTP 协议(protocol),我不是这方面的专家)在请求正文中的 /
和 :
字符方面存在问题。我必须赞扬Studiosus在Polyglot issue report上的回答.
关于ios - 如何从 Swift 3 获取 MS Translator 访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40109640/