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
BasicResponseHandleronly returns your data if a success code (2xx) was returned. However, you can very easily write your ownResponseHandlerto always return the body of the response as aString, e.g.Alternatively, you can use the other overloaded execute method on
HttpClientwhich does not require aResponseHandlerand returns you theHttpResponsedirectly. Then callEntityUtils.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 theHttpStatusclass. E.g. code ‘403’ isHttpStatus.SC_FORBIDDEN. You can take particular actions as relevant to your application depending on the status code returned.