如何获得HttpResponseException背后的实际错误?

Dan*_*scu 8 java apache post http

我正在使用Apache HttpComponents Client来POST一个返回JSON的服务器.问题是如果服务器返回400错误,我似乎无法告诉Java错误是什么(到目前为止不得不求助于数据包嗅探器 - 荒谬).这是代码:

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 ""
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?必须有一种简单的方法来获取400错误的消息.这是基本的.

ZZ *_*der 13

为什么使用BasicResponseHandler()?处理程序正在为您执行此操作.该处理程序只是一个示例,不应在实际代码中使用.

您应该编写自己的处理程序或在没有处理程序的情况下调用execute.

例如,

        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
        }
Run Code Online (Sandbox Code Playgroud)