gpt4 book ai didi

ios - Alamofire 返回 .Success on error HTTP 状态代码

转载 作者:IT王子 更新时间:2023-10-29 05:06:58 27 4
gpt4 key购买 nike

我有一个非常简单的场景,我正在努力应对。我正在使用 Alamofire 在 rest API 上注册用户。第一次调用注册成功,用户可以登录。第二次调用,当尝试使用相同的电子邮件地址注册时,服务器应返回 HTTP 状态代码 409。然而,Alamofire 返回一个带有空请求和响应的 .Success 。我已经用 postman 测试了这个 API,它正确地返回了 409。

为什么 Alamofire 不返回 .Failure(error),其中错误包含状态代码信息等?

这是我每次都使用相同输入运行的调用。

Alamofire.request(.POST, "http://localhost:8883/api/0.1/parent", parameters: registrationModel.getParentCandidateDictionary(), encoding: .JSON).response(completionHandler: { (req, res, d, e) -> Void in
print(req, res, d, e)
})

最佳答案

来自 Alamofire manual :

Validation

By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling validate before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.

您可以再次使用手册中的 validate 方法手动验证状态码:

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { response in
print(response)
}

或者您可以使用不带参数的 validate 半自动验证状态代码和内容类型:

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}

关于ios - Alamofire 返回 .Success on error HTTP 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34737574/

27 4 0