cURL
既然您有示例,让我们使用 Alamofire 的有用调试工具。
让我们打破你当前的代码:
let headers = ["Content-Type": "application/x-www-form-urlencoded"]
let params = ["grant_type": "client_credentials"]
let request = Alamofire.request("https://test.api.amadeus.com/v1/security/oauth2/token",
method: .post,
parameters: params,
encoding: JSONEncoding.default,
headers: headers).authenticate(user: "API", password: "API")
print(request.debugDescription)
request.responseJSON { response in
debugPrint(response)
let result = response.result.value
print(result)
}
输出:
$>curl -v \
-X POST \
-u API:API \
-H "Accept-Language: fr-US;q=1.0, en;q=0.9, fr-FR;q=0.8" \
-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
-H "User-Agent: iOSTest/1.0 (nt.iOSTest; build:1; iOS 12.2.0) Alamofire/4.8.1" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "{\"grant_type\":\"client_credentials\"}" \
"https://test.api.amadeus.com/v1/security/oauth2/token"
让我们一步一步来:我们应该忘记 Accept-Encoding、User-Agent 和 Accept-Language 标头。我稍后会跳过它们。
我们看到-d
(data into httpBody) 是错误的。
让我们改变一下:encoding: JSONEncoding.default
到encoding: URLEncoding(destination: .httpBody)
. 另外,这是有道理的,因为在内容类型中我们说它是 url 编码的。
我们得到:
$>-d "grant_type=client_credentials"
似乎更好。
我们看到-u API:API \
对应的.authenticate(user: "API", password: "API")
。如果服务器不管理这样的身份验证,我们可能希望将其删除,并将其放入参数中。所以现在,让我们更改参数:
let params = ["grant_type": "client_credentials",
"client_id" : "APIKey",
"client_secret" : "APISecret"]
我们得到:
$>-d "client_id=APIKey&client_secret=APISecret&grant_type=client_credentials" \
它应该工作。
顺序不一样,但服务器不应该关心它。它应该是键/访问而不是索引/访问。
所以最后:
let headers = ["Content-Type": "application/x-www-form-urlencoded"]
let params = ["grant_type": "client_credentials",
"client_id" : "APIKey",
"client_secret" : "APISecret"]
let request = Alamofire.request("https://test.api.amadeus.com/v1/security/oauth2/token",
method: .post,
parameters: params,
encoding: URLEncoding(destination: .httpBody),
headers: headers)
print(request.debugDescription)
request.responseJSON { response in
debugPrint(response)
let result = response.result.value
print(result)
}
输出(带有跳过的标题):
$ curl -v \
-X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "client_id=APIKey&client_secret=APISecret&grant_type=client_credentials" \
"https://test.api.amadeus.com/v1/security/oauth2/token"