ios 有什么方法可以在 HTTP 错误期间获取响应正文?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35088237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Any way to get the response body during HTTP errors?
提问by Kevin DiTraglia
I'm hitting an API that will occasionally throw a HTTP 403 error, and the response body can give some extra information in the form of json, however for the life of me I can't seem to get the information back out from the Alamofire response objects. I see the information in developer tools if I hit the API via chrome. Here's my code:
我正在使用一个偶尔会抛出 HTTP 403 错误的 API,并且响应主体可以以 json 的形式提供一些额外的信息,但是对于我的生活,我似乎无法从 Alamofire 取回信息响应对象。如果我通过 chrome 访问 API,我会在开发人员工具中看到信息。这是我的代码:
Alamofire.request(mutableURLRequest).validate().responseJSON() {
(response) in
switch response.result {
case .Success(let data):
if let jsonResult = data as? NSDictionary {
completion(jsonResult, error: nil)
} else if let jsonArray = data as? NSArray {
let jsonResult = ["array" : jsonArray]
completion(jsonResult, error: nil)
}
case .Failure(let error):
//error tells me 403
//response.result.data can't be cast to NSDictionary or NSArray like
//the successful cases, how do I get the response body?
}
I've queried pretty much every object attached to the response, but it doesn't seem to give me the response body back in the case of HTTP errors. Is there a work-around or something I'm missing here?
我已经查询了几乎所有附加到响应的对象,但在出现 HTTP 错误的情况下,它似乎没有给我返回响应正文。是否有解决方法或我在这里缺少的东西?
回答by Kevin DiTraglia
I asked this question on their github page and got an answer from cnoon:
我在他们的 github 页面上问了这个问题,并从 cnoon 得到了答案:
swift 2:
快速2:
if let data = response.data {
let json = String(data: data, encoding: NSUTF8StringEncoding)
print("Failure Response: \(json)")
}
swift 3:
快速3:
if let data = response.data {
let json = String(data: data, encoding: String.Encoding.utf8)
print("Failure Response: \(json)")
}
https://github.com/Alamofire/Alamofire/issues/1059
https://github.com/Alamofire/Alamofire/issues/1059
I just left out the encoding part, by doing this you are able to get the response json even in the case of errors.
我只是省略了编码部分,通过这样做,即使在出现错误的情况下,您也可以获得响应 json。
回答by Medhi
Swift 5 to get body response easily in DefaultDataResponse extension :
Swift 5 在 DefaultDataResponse 扩展中轻松获得正文响应:
String(data: data!, encoding: String.Encoding.utf8)