【问题标题】:Alamofire Content-Type application/json for PUT method用于 PUT 方法的 Alamofire Content-Type application/json
【发布时间】:2016-07-25 11:04:23
【问题描述】:

我现在正在寻找在 Alamofire Content-Type application/json 中为 PUT 方法添加 content-type: application/json 的解决方案。我已经开发如下,但无法正常工作。

        Alamofire.request(.PUT, Config.preferenceURL, parameters: param, headers: headers)
            .validate(contentType: ["application/json"])
            .responseJSON { response in
                let swiftyJsonVar = JSON(response.result.value!)
                print(swiftyJsonVar)
                if (swiftyJsonVar["success"]) {

                }

                JHProgressHUD.sharedHUD.hide()
        }

【问题讨论】:

  • 显示/添加你得到的错误日志。

标签: ios json swift alamofire


【解决方案1】:

您需要在request 方法中指定encoding: .JSON。否则,它会将您的参数编码为 URL 中的查询参数。通过使用.JSON 编码,将自动为您设置Content-Type 标头。

Alamofire.request(.PUT, Config.preferenceURL, parameters: param, encoding: .JSON, headers: headers)

您还可以使用debugPrint API 打印出与您发送到服务器的请求等效的cURL 命令。

let request = Alamofire.request(.PUT, Config.preferenceURL, parameters: param, encoding: .JSON, headers: headers)
debugPrint(request)

干杯。 ?

【讨论】:

  • "Content-Type 标头将自动为您设置。" 这在 4.0 上是否更改?即使我使用JSONEncoding.default,我也必须手动添加它
【解决方案2】:

添加content-type: application/json 如下所示:-

let URL = NSURL(string: "https://httpbin.org/post")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"

let parameters = ["foo": "bar"]

do {
    mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
} catch {
    // No-op
}

mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

Alamofire.request(mutableURLRequest)

More detail here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2020-04-23
    • 2020-11-14
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 2012-01-30
    相关资源
    最近更新 更多