【问题标题】:Alamofire post request does not change headersAlamofire 发布请求不会更改标题
【发布时间】:2017-08-14 14:17:00
【问题描述】:

在我阅读了有关 Alamofire 发布请求的文档后,我设法实现了它以供我使用,但发布请求不断返回我的代码 400,这意味着该请求是错误的。

Following steps here

我的实现看起来很像:

 let parameters = ["username": name, "password": hashPass]
        let url = URL(string: LOGIN_URL)!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
        } catch {

        }
        request.setValue("application/json;charest=utf-8", forHTTPHeaderField: "Content-Type")

        Alamofire.request(request).responseJSON { response in
            print("Get default graph request \(response.request!)")
            print("Get default graph response \(response.response!)")

            if let message = response.result.value {
                SessionMenager.Instance.token = message as! String
                completion(true)
            } else {
                completion(false)
            }
        }

每当我调试代码时,我都能看到"Content-Type" = "text/html"

我该如何解决这个问题? 提前致谢!

编辑

这是一个带有URLSession 的版本:

let stringOp = StringOperations.init()
            let md5Data = stringOp.MD5(string:pass)
            let hashPass = md5Data!.map { String(format: "%02hhx", $0) }.joined()

            let json: [String: Any] = ["username": name,
                                       "passwordHash": hashPass ]

            let jsonData = try? JSONSerialization.data(withJSONObject: json)

            let url = URL(string: LOGIN_URL)!
            var request = URLRequest(url: url)
            request.httpMethod = "POST"

            // insert json data to the request
            request.httpBody = jsonData
            request.setValue("application/json;charest=utf-8", forHTTPHeaderField: "Content-Type")

            print ("REQUEST : \(request)")
            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data, error == nil else {
                    print(error?.localizedDescription ?? "No data")
                    return
                }

                if let httpResponse = response as? HTTPURLResponse {
                    print("POST : code -  \(httpResponse.statusCode)")
                }

                let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
                if let responseJSON = responseJSON as? [String: Any] {
                    print(responseJSON)
                    let message:String = responseJSON["message"] as! String
                    if !(message.range(of: "ERROR") != nil){
                        SessionMenager.Instance.token = message
                        completion(true)
                    }
                } else{
                    print(error.debugDescription)

                }
            }
        task.resume()

第二次编辑

好吧!我已经弄清楚了如何以一种好的方式做到这一点:

  let stringOp = StringOperations.init()
        let md5Data = stringOp.MD5(string:pass)
        let hashPass = md5Data!.map { String(format: "%02hhx", $0) }.joined()

        let json: [String: Any] = ["username": name, "passwordHash": hashPass ]

        let jsonData = try? JSONSerialization.data(withJSONObject: json)

        let url = URL(string: LOGIN_URL)!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        request.httpBody = jsonData
        request.setValue("application/json;charest=utf-8", forHTTPHeaderField: "Content-Type")

        Alamofire.request(request).responseJSON { response in
            print("Get default graph request \(response.request!)")
            print("Get default graph response \(response.response!)")

            let json = JSON(response.data!)
            let message = json["message"]
            if !(message.stringValue.range(of: "ERROR") != nil) {
                SessionMenager.Instance.token = message.stringValue
                completion(true)
            } else {
                completion(false)
            }
        }

【问题讨论】:

标签: swift swift3 alamofire


【解决方案1】:

您可以使用ParameterEncoding 设置正文编码类型。 https://github.com/Alamofire/Alamofire#parameter-encoding

Alamofire.request(LOGIN_URL, method: .post, parameters:json, encoding: JSONEncoding.default).responseJSON { ... }

这也可以通过URLRequestConvertible 实现

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 2020-09-30
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多