我怎么能落后的Htt presponseException实际的错​​误? [英] How can I get the actual error behind HttpResponseException?

查看:110
本文介绍了我怎么能落后的Htt presponseException实际的错​​误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Apache HttpComponents客户端发布到返回JSON的服务器。问题是,如果服务器返回一个400错误,我似乎没有告诉人从Java是错误的方式(不得不求助于迄今为止包嗅探器 - 可笑)。这里是code:

I'm using Apache HttpComponents Client to POST to a server that returns JSON. The problem is that if the server returns a 400 error, I seem to have no way of telling what the error was from Java (had to resort to a packet sniffer so far - ridiculous). Here is 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 ""
}

我是什么做错了吗?必须有一种简单的方法来获得一个400错误的消息。这是基本的。

What am I doing wrong? There must be an easy way to get the message of a 400 error. This is elementary.

推荐答案

为什么使用BasicResponseHandler()?该处理器是做了你。该处理程序仅仅是一个例子,不应该在实际code可以使用

Why do you use BasicResponseHandler()? The handler is doing that for you. That handler is just an example and shouldn't be used in real code.

您应该要么编写自己的处理程序或调用execute没有处理程序。

You should either write your own handler or call execute without a handler.

例如,

        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
        }

这篇关于我怎么能落后的Htt presponseException实际的错​​误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆