将 httpBody 转换为 x-www-urlencoded
Convert httpBody for x-www-urlencoded
我正在对服务器进行 POST 调用,但 Alamofire 总是将正文作为 JSON 发送,而不是作为 URL 编码的形式发送,我知道为了编码正文我必须插入 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>")
我正在对服务器进行 POST 调用,但 Alamofire 总是将正文作为 JSON 发送,而不是作为 URL 编码的形式发送,我知道为了编码正文我必须插入 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>")