Search code examples
javaandroidhttpclienthttp-status-code-403

Android getting response after 403 in HttpClient


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


Solution

  • 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.