我尝试连接第三方API,该第三方API需要使用身份验证令牌作为使用Alamofire 4的JSON正文的POST请求的查询参数。
此处提出了类似的问题:Multiple encoding types for Alamofire Request
我试图使用Alamofire 4(答案使用Alamofire 3)来实现接受的答案。
这就是我正在做的事情:
let url = URL(string: urlString)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let bodyParameters: [String: AnyObject] = [
"inviter": inviterId as AnyObject,
"invitee": inviteeId as AnyObject
]
let requestWithBody = try Alamofire.JSONEncoding.default.encode(urlRequest, with: bodyParameters)
let queryParameters: [String: AnyObject] = [
"api_token": tokenString as AnyObject
]
var compositeRequest = try Alamofire.URLEncoding.default.encode(urlRequest, with: queryParameters)
compositeRequest.httpBody = requestWithBody.httpBody
return compositeRequest
代码编译并执行正常。但是,当我执行请求并将response.request打印到控制台时,请求URL不包含查询参数。
答案 0 :(得分:0)
原版的这个版本似乎对我有用(AF4 / Swift4):
fileprivate func multiEncodedURLRequest(
method: HTTPMethod,
requestURL: URL,
parameters: Parameters,
bodyParameters: Parameters) -> URLRequest
{
let request = URLRequest(url: requestURL)
do {
var urlRequest = try URLEncoding.default.encode(request, with: parameters)
var bodyRequest = try JSONEncoding.default.encode(request, with: bodyParameters)
urlRequest.httpMethod = method.rawValue
urlRequest.httpBody = bodyRequest.httpBody
return urlRequest
}
catch {
return request
}
}