代码之家  ›  专栏  ›  技术社区  ›  Dan Dascalescu

如何获取httpResponseException背后的实际错误?

  •  8
  • Dan Dascalescu  · 技术社区  · 17 年前

    我使用Apachehttpcomponents客户机发布到一个返回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个错误的消息。这是基本的。

    2 回复  |  直到 17 年前
        1
  •  12
  •   ZZ Coder    17 年前

    为什么使用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
            }
    
        2
  •  1
  •   pstanton    17 年前

    如果在为ResponseBody赋值时引发异常,则ResponseBody始终为空。

    此外,它是实现的特定行为——即Apachehttpclient。

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

    我将加载httpclient的源代码并调试它。

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

    希望有帮助。

    推荐文章