1

I send requests to the server like so

public HttpResponse post(String URN, String entity) throws IOException {
    HttpPost httpPost = new HttpPost(URL + URN);
    httpPost.setHeader("Content-type", "application/json");
    httpPost.setHeader("Accept", "application/json");
    httpPost.setEntity(new StringEntity(entity, HTTP.UTF_8));
    return httpClient.execute(httpPost, httpContext);
}

To create a new account a phone number is sent to the server and is validated. If a number is not valid a 400 BAD REQUEST error is returned.

Within the response from the server a JSON object is returned in the content. This has the details of why the 400 error is returned. A typical JSON response would look like this

{"dev_message": "The number 93015205229804 isn't a valid mobile number.", "user_message": "Invalid phone number", "error_code": 108}

The execute method throws an IOException when a 400 error is returned. How can I go about getting the message from the HttpResponse if an error is automatically thrown?

jiduvah
  • 5,108
  • 6
  • 39
  • 55
  • Have you tried surrounding `httpClient.execute` in a try-catch statement? You can get the error message from the exception that is thrown. And, if memory serves me right, a 400 means bad syntax so there's an error with your request. – ebarrenechea Feb 21 '13 at 15:45
  • To be clearer. I can send requests fine. I am trying to handler the response from the server when an invalid number is sent. Should the server be returning 400 in this case? – jiduvah Feb 21 '13 at 15:47
  • Using a 400 error wouldn't be a problem I think, but it may cause confusion if you eventually open up your API to other developers. Just to be clear 400 means bad syntax and your request has a valid syntax, the problem is with the data. You should have a look at how other services deal with error codes. Twitter is a very good example and you can see their documentation [here](https://dev.twitter.com/docs/error-codes-responses) – ebarrenechea Feb 21 '13 at 15:56
  • Twitter uses 422 Unprocessable Entity. Would that make more sense? How would I get the message from the error that is thrown? – jiduvah Feb 21 '13 at 16:11
  • never mind I found an answer http://stackoverflow.com/questions/7025213/android-getting-response-after-403-in-httpclient?rq=1 – jiduvah Feb 21 '13 at 16:18

0 Answers0