简体   繁体   English

Alamofire-错误的要求

[英]Alamofire - Bad request

I am afraid I cannot share the API url. 恐怕我无法共享API网址。 But I have checked on Postman , it works. 但是我检查了邮递员 ,它可以工作。 It is a POST request and following is the response : 这是一个POST请求,以下是响应:

{
    "user_key": "b0aebdedb15e2beaaf479ca3c4f8227e8e970681"
}  

Postman screenshot : 邮递员截图:

在此处输入图片说明

In code, this is the request I am making using Alamofire : 在代码中,这是我使用Alamofire发出的请求:

Alamofire.request("some url", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: ["Content-Type":"application/json"])
            .responseObject { (response: DataResponse<User>) in

                let userResponse = response.result.value
                print("")
    }

But userResponse comes to be nil. 但是userResponse变为零。 This is the User object : 这是User对象:

import ObjectMapper

class User: Mappable {

    var authToken: String?

     required init?(map: Map) {

    }

    func mapping(map: Map) {
        self.authToken <- map["user_key"]
    }


}

I am using ObjectMapper here. 我在这里使用ObjectMapper

Assuming the it is not a JSON object, I tried to handle it as a String : 假设它不是JSON对象,我尝试将其作为String处理:

 Alamofire.request("some url", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: ["Content-Type":"application/json"])
            .responseString { (response: DataResponse<String>) in
                let dataUser = response.data as! Any
                let dataUser1 = response.data as! AnyObject
                let error = response.error
                let code = response.response?.statusCode
                print(response.value)
                print(response.result.value)
        }  

Still, nothing. 依然没有。 I am not able to retrieve the value. 我无法检索该值。 The status code however comes out to be 400 (bad request). 但是状态码显示为400(错误请求)。 What exactly is it ? 到底是什么? JSON object or String ? JSON对象还是String How do I fix this ? 我该如何解决 ?

Just try to replace 只是尝试更换

this URLEncoding.httpBody to JSONEncoding.default 将此URLEncoding.httpBodyJSONEncoding.default

JSONEncoding.default JSONEncoding.default

Uses JSONSerialization to create a JSON representation of the parameters object, which is set as the body of the request. 使用JSONSerialization创建参数对象的JSON表示形式,该对象设置为请求的主体。 The Content-Type HTTP header field of an encoded request is set to application/json . 编码请求的Content-Type HTTP标头字段设置为application/json

Alamofire reference Alamofire参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM