【问题标题】:Android getting response after 403 in HttpClientAndroid 在 HttpClient 中获得 403 后的响应
【发布时间】:2011-10-24 21:49:54
【问题描述】:

我有这样的代码:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(server);

try {
    JSONObject params = new JSONObject();
    params.put("email", email);

    StringEntity entity = new StringEntity(params.toString(), "UTF-8");
    httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
    httpPost.setEntity(entity);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpClient.execute(httpPost, responseHandler);
    JSONObject response = new JSONObject(responseBody);
        fetchUserData(response);

    saveUserInfo();

    return true;
} catch (ClientProtocolException e) {
    Log.d("Client protocol exception", e.toString());
    return false;
} catch (IOException e) {
    Log.d`enter code here`("IOEXception", e.toString());
    return false;
} catch (JSONException e) {
    Log.d("JSON exception", e.toString());
    return false;
}

即使我有 HTTP 403 Forbidden to get error message,我也希望得到响应

【问题讨论】:

  • HTTP 客户端库中的常见问题,感谢提问......

标签: java android httpclient http-status-code-403


【解决方案1】:

BasicResponseHandler 仅在返回成功代码 (2xx) 时才会返回您的数据。但是,您可以非常轻松地编写自己的 ResponseHandler 以始终将响应的正文作为 String 返回,例如

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
    @Override
    public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
        return EntityUtils.toString(response.getEntity());
    }
    };

或者,您可以在HttpClient 上使用other overloaded execute method,它不需要ResponseHandler,并直接返回HttpResponse。然后以同样的方式调用EntityUtils.toString(response.getEntity())

要获取响应的状态代码,您可以使用HttpResponse.getStatusLine().getStatusCode() 并与HttpStatus 类中的静态整数之一进行比较。例如。代码“403”是HttpStatus.SC_FORBIDDEN。您可以根据返回的状态代码采取与您的应用程序相关的特定操作。

【讨论】:

  • 非常感谢您的回答!
【解决方案2】:

根据BasicResponseHandler的文档:

如果响应不成功(>= 300 状态码),则抛出 HttpResponseException

你可以捕捉到这种类型的异常(注意:你已经捕捉到这个异常的超类型ClientProtocolException)并且你可以在那个catch块中放置一些自定义逻辑来在遇到错误情况时创建/保存一些响应,比如403。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    相关资源
    最近更新 更多