在HTTP错误期间获取响应正文的任何​​方法? [英] Any way to get the response body during HTTP errors?

查看:227
本文介绍了在HTTP错误期间获取响应正文的任何​​方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在点击一个偶尔会抛出HTTP 403错误的API,而响应机构可以以json的形式提供一些额外的信息,但是对于我的生活,我似乎无法将信息退出来自Alamofire的响应对象。如果我通过chrome访问API,我会在开发人员工具中看到这些信息。这是我的代码:

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:

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

我几乎查询了附加到响应的每个对象,但它没有在HTTP错误的情况下,似乎给了我回复主体。是否有解决方法或我在这里缺少的东西?

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?

推荐答案

我在他们的github页面上问了这个问题并得到了一个从cnoon回答:

I asked this question on their github page and got an answer from cnoon:

swift 2:

if let data = response.data {
    let json = String(data: data, encoding: NSUTF8StringEncoding)
    print("Failure Response: \(json)")
}

swift 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

我刚刚省略了编码部分这样即使出现错误,你也能得到响应json。

I just left out the encoding part, by doing this you are able to get the response json even in the case of errors.

这篇关于在HTTP错误期间获取响应正文的任何​​方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆