ios - 将 httpBody 转换为 x-www-urlencoded

标签 ios swift xcode swift4 alamofire

我正在对服务器进行 POST 调用,但 Alamofire 始终将正文作为 JSON 而不是作为编码的表单 URL 发送,我知道为了对正文进行编码,我必须插入 data(使用: .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/

相关文章:

ios - InstantiateViewController(标识符 :creator:)' is only available in iOS 13. 0 或更新版本

ios - 如何在带有 cornerRadius 的 UIView 上绘制 1 像素宽的平滑边框?

ios - 如何强制 Flutter 使用新的开发者证书?

ios - 当我尝试存档时,无法创建 ipa 文件

ios - 在 xcode 中导出 ipa

ios - NSString 到 NSDictionary 作为对象

ios - MapBox iOS SDK - 第一步

ios - animateWithDuration 中的自定义缓动?

swift - 赋值前验证值不相等

ios - 迁移到惯用的 Swift 2 的 list (也就是 Swift 2 转换指南在哪里)?