【问题标题】:How can I get the actual error behind HttpResponseException?如何获得 HttpResponseException 背后的实际错误?
【发布时间】:2010-12-02 04:45:47
【问题描述】:

我正在使用 Apache HttpComponents 客户端 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 ""
}

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

【问题讨论】:

    标签: java apache http post


    【解决方案1】:

    为什么要使用 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
            }
    

    【讨论】:

    • 这行得通;谢谢。剩下的就是将 responseBody InputStream 转换成一个字符串。
    • 您可以使用 EntityUtils.toString(entity) 将其转换为字符串。它为您处理字符转换。顺便说一句,JSON 错误应该返回 200。否则,您无法从浏览器获得响应。
    • 请在此处提供帮助 - stackoverflow.com/questions/1490341/…
    【解决方案2】:

    如果在为其赋值时抛出异常,responseBody 将始终为 null。

    此外,它是实现的特定行为 - 即 Apache HttpClient。

    看起来它没有维护异常中的任何详细信息(显然)。

    我会加载 HttpClient 的源代码并对其进行调试。

    但首先检查 e.getCause() 中是否有任何内容...

    希望有帮助。

    【讨论】:

    • 请记住,它是开源的 - 如果需要,您可以随时更改或贡献。
    • e.getCause() 返回空值。我知道它是开源的,但我是 Java 的初学者,这是可以为 HTTP 客户端库映像的最基本功能:给我错误
    • 很高兴您找到了答案(上图)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多