【问题标题】:Convert httpBody for x-www-urlencoded将 httpBody 转换为 x-www-urlencoded
【发布时间】:2020-04-06 20:42:00
【问题描述】:

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

【问题讨论】:

标签: ios swift xcode swift4 alamofire


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-06-11
    • 2015-08-16
    • 2020-10-06
    • 2019-12-04
    • 2021-06-15
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多