我正在对服务器进行POST调用,但是Alamofire始终将正文作为JSON发送,而不是作为Form URL Encoded发送,我确实知道在编码正文时必须插入data(using: .utf8, allowLossyConversion: false)
,但是我不知道哪里。
如何修复我的代码?
这是我的实际代码:
func asURLRequest() throws -> URLRequest {
let url = try DBank.StagingServer.baseUrl.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
// HTTP Method
urlRequest.httpMethod = method.rawValue
// Common Headers
headers.forEach { (field, value) in
urlRequest.setValue(value, forHTTPHeaderField: field)
}
// Parameters
if let parameters = parameters {
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
}
最佳答案
我猜你有如下响应处理程序:
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding(destination: .queryString), headers: headers)
.validate(statusCode: 200..<300)
.responseString { response in
//response.result.value will contain http response from your post call
}
根据此响应的结果,您将设置:
UserDefaults.standard.set("<result>", forKey: "<token>")
关于ios - 将httpBody转换为x-www-urlencoded,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59321826/