我正在尝试学习使用/不使用库来调用 API。但这里的问题让我很困惑。
我有这样的参数:
let parameters: [String:String] =
["key":"MY_KEY" ,
"q":sourceText,
"source": sourceLanguage),
"target": target)]
let headers: HTTPHeaders = [ "Content-type": "application/json"]
我调用这样的电话:
Alamofire.request(urlString, method: HTTPMethod.post, parameters: parameters, headers: headers)
.responseJSON{ response in
guard response.result.error == nil else {
print("error calling POST on /todos/1")
print(response.result.error!)
return
}
// make sure we got some JSON since that's what we expect
guard let json = response.result.value as? [String: Any] else {
print("didn't get todo object as JSON from API")
print("Error: \(response.result.error)")
return
}
由此,我收到错误 403,表示我没有有效的 API key (我使用 postman 测试了该 key ,并且没问题)。
经过多次努力,我必须将代码更改为这样
let stringparams = "key=MY_KEY&q=\(sourceText)&source=\(sourceLanguage)&target=\(target)"
request.httpBody = stringparams.data(using: String.Encoding.utf8)
并使用这个:Alamofire.request(request) 有用! 我正在使用 Google Cloud Translation api。 Web 使用 REST api,如下所述:https://cloud.google.com/translate/docs/reference/translate
那么为什么我不能使用参数作为字典,但使用字符串(如 formdata)可以在这里工作?
我的猜测是 Alamofire 没有为参数请求提供正确的 BODY,因为其他参数没问题。但我不知道为什么。 我认为 Google 应该接受他们提到的 json 参数,而不是使用表单数据?我确实尝试了原始方法,但它不适用于 JSON。
最佳答案
从实际对您有用的内容来看,您似乎需要以与查询相同的样式对参数进行编码。试试这个:
struct ParameterQueryEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = parameters?
.map { "\($0)=\($1)" }
.joined(separator: "&")
.data(using: .utf8)
return request
}
}
然后您应该能够执行之前的原始调用:
Alamofire.request(urlString,
method: HTTPMethod.post,
parameters: parameters,
encoding: ParameterQueryEncoding(),
headers: headers)
.responseJSON { response in
...
}
关于swift - 无法使用 params 作为字典与 Swift 4 和 Alamofire 发出发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49571928/