I am using Apache HttpComponents Client to Publish to some server that returns JSON. However , when the server returns a 400 error, I appear to possess not a way of telling exactly what the error was from Java (needed to turn to a packet sniffer to date - absurd). This is actually the code:

HttpClient httpclient = new DefaultHttpClient();
params.add(new BasicNameValuePair("format", "json"));
params.add(new BasicNameValuePair("foo", bar));

HttpPost httppost = new HttpPost(uri);
// this is how you set the body of the POST request
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

String responseBody = "";
try {
    // Create a response handler
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    responseBody = httpclient.execute(httppost, responseHandler);
} catch(HttpResponseException e) {
    String error = "unknown error";
    if (e.getStatusCode() == 400) {
        // TODO responseBody and e.detailMessage are null here, 
        // even though packet sniffing may reveal a response like
        // Transfer-Encoding: chunked
        // Content-Type: application/json
        //
        // 42
        // {"error": "You do not have permissions for this operation."}
        error = new JSONObject(responseBody).getString("error");  // won't work
        }
    // e.getMessage() is ""
}

What shall we be held doing wrong? There has to be a good way to obtain the message of the 400 error. This really is elementary.

So why do you utilize BasicResponseHandler()? The handler does that for you personally. That handler is simply a good example and should not be utilized in tangible code.

You need to either write your personal handler or call execute with no handler.

For instance,

        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        responseBody = entity.getContent();

        if (statusCode != 200) {
            // responseBody will have the error response
        }

responseBody will be null if the exception is tossed while setting something into it.

on top of that it's specific behavior from the implementation - ie Apache HttpClient.

It appears enjoy it does not maintain the more information within the exception (clearly).

I'd stock up the origin code for HttpClient and debug that.

however see if there's anything within the e.getCause()...

hope that can help.