将httpBody转换为x-www-urlencoded

时间:2019-12-13 11:36:34

标签: ios swift xcode swift4 alamofire

我正在对服务器进行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))
        }
    }

1 个答案:

答案 0 :(得分:0)

我猜您有如下响应处理程序:

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>")