【问题标题】:Alamofire - Bad requestAlamofire - 错误的请求
【发布时间】:2019-02-09 03:07:12
【问题描述】:

恐怕我无法分享 API 网址。但是我检查了 Postman,它可以工作。这是一个 POST 请求,以下是响应:

{
    "user_key": "b0aebdedb15e2beaaf479ca3c4f8227e8e970681"
}  

邮递员截图:

在代码中,这是我使用 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("")
    }

但是 userResponse 变成了 nil。这是 User 对象:

import ObjectMapper

class User: Mappable {

    var authToken: String?

     required init?(map: Map) {

    }

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


}

我在这里使用ObjectMapper。

假设它不是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)
        }  

仍然没有。我无法检索该值。然而,状态码是 400(错误请求)。 它到底是什么? JSON 对象或 String ?我该如何解决这个问题?

【问题讨论】:

  • 双重检查请求method、encoding、endPoint 和headers 与Alamofire 请求和Postman 一起发送。如果后端的人可以接触到,那么稍微惹恼他是个好主意:)
  • 错误400一般表示服务器拒绝不接受你的请求所以没有返回用户数据,这就是为什么userResponse为nil。
  • @Kamran : 如何检查 Postman 的编码?
  • @IgorN:是的。我已经提到过。
  • 检查你的参数并尝试将这个URLEncoding.httpBody替换为JSONEncoding.default

标签: ios swift alamofire postman objectmapper


【解决方案1】:

尝试替换

这个URLEncoding.httpBody 到JSONEncoding.default

JSONEncoding.default

使用JSONSerialization 创建参数对象的JSON 表示,该对象被设置为请求的主体。编码请求的Content-Type HTTP 标头字段设置为application/json。

Alamofire reference

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 2017-08-20
    • 2016-02-23
    • 2023-03-20
    • 2016-03-29
    • 2017-10-29
    • 2015-11-18
    • 1970-01-01
    相关资源
    最近更新 更多