Android gets 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 get a response even if I have HTTP 403 Forbidden to receive an error message

+8
source share
2 answers

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

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

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

To get the response status code, you can use HttpResponse.getStatusLine().getStatusCode() and compare it with one of the static ints in the HttpStatus class. For example. code '403' is equal to HttpStatus.SC_FORBIDDEN . You can take certain actions specific to your application, depending on the status code returned.

+12
source

According to the documentation for BasicResponseHandler :

If the response is unsuccessful (> = status code 300), an HttpResponseException thrown.

You can catch this type of exception (note: you are already ClientProtocolException supertype of this ClientProtocolException exception), and you can put some user logic in this catch block to create / save some response when you encounter an error situation, such as 403.

+2
source

All Articles