Alamofire发帖请求不会更改标题

时间:2017-03-22 12:49:21

标签: swift swift3 alamofire

在我阅读了有关Alamofire帖子请求的文档后,我已经设法为我的用法实现它,但是post请求不断返回代码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()

第二次编辑

Al'right!我已经弄清楚如何以我的方式做到这一点:

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

1 个答案:

答案 0 :(得分:0)

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

ParameterEncoding

这可以通过Alamofire.request(LOGIN_URL, method: .post, parameters:json, encoding: JSONEncoding.default).responseJSON { ... } 来实现