2016-10-18 47 views
0

我正在尝试使用Swift 3的MS翻译器API(现在在操场上玩,但目标平台是iOS)。但是,当我试图获取OAuth2的访问令牌时,我陷入了困境。我有以下代码(我试图端口从例子中的代码在Obtaining an access token):如何从Swift 3获取MS翻译器访问令牌?

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头)时,我得到了相同的响应。但是,当我将邮递员用户界面中的主体类型更改为application/x-www-form-urlencoded,并通过其UI将请求详细信息键入为键值对时,调用成功。现在看来,我在信息格式上做错了什么,或者甚至是Swift URLRequest/URLSession API的问题,但是,我无法控制什么。请有人帮助我吗?谢谢。

回答

0

好吧,等一些更绝望的谷歌搜索和试验后,我发现我的错误。对于后代:

问题在于编码参数在PUT http请求的主体中。相反的:

let scope = "http://api.microsofttranslator.com" 
      .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! 

我必须使用以下命令:

let scope = "http://api.microsofttranslator.com" 
      .addingPercentEncoding(withAllowedCharacters: 
         CharacterSet(charactersIn: ";/?:@&=$+{}<>,").inverted)! 

似乎API(或HTTP协议,我不是这方面的专家)有/问题和:字符请求正文。我必须赞扬Studiosus在Polyglot issue report上的回答。