开发者

Android getting response after 403 in HttpClient

开发者 https://www.devze.com 2023-03-27 02:16 出处:网络
I have a code like this: HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(server);

I have a code like this:

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

And i want to have a response even if I have HTTP 403 Forbidden to get error message


The BasicResponseHandler only returns your data if a success code (2xx) was returned. However, you can very easily write your own ResponseHandler to always return the body of the response as a String, e.g.

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

Alternatively, you can use the other overloaded execute method on HttpClient which does not require a ResponseHandler and returns you the HttpResponse directly. Then call EntityUtils.toString(response.getEntity()) in the same way.

To get the status code of a response, you can use HttpResponse.getStatusLine().getStatusCode() and compare to to one of the static ints in the HttpStatus class. E.g. code '403' is HttpStatus.SC_FORBIDDEN. You can take particular actions as relevant to your application depending on the status code returned.


According to the documentation for BasicResponseHandler:

If the response was unsuccessful (>= 300 status code), throws an HttpResponseException.

You could catch this type of exception (Note: you are already catching the supertype of this exception ClientProtocolException) and you could put some custom logic in that catch block to create / save some response when you encounter an error situation, such as the 403.

0

精彩评论

暂无评论...
验证码 换一张
取 消