2009-09-29 104 views
8

我正在使用Apache HttpComponents客户端来POST到返回JSON的服务器。问题是,如果服务器返回一个400错误,我似乎无法告诉Java错误是什么(不得不求助于一个数据包嗅探器 - 这很荒谬)。这里是代码:如何获取HttpResponseException后面的实际错误?

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错误的消息。这是基本的。

回答

12

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

这工作;谢谢。剩下的只是将responseBody InputStream转换为String。 – 2009-09-29 06:07:03

+1

您可以使用EntityUtils.toString(实体)将其转换为字符串。它为你处理字符转换。顺便说一句,JSON错误应该返回200.否则,你无法从浏览器得到响应。 – 2009-09-29 11:15:48

+0

请帮助这里 - http://stackoverflow.com/questions/1490341/how-can-i-get-the-actual-error-behind-httpresponseexception – 2013-12-18 10:51:18

1

如果在为其分配值时引发异常,那么responseBody将始终为空。

除了它是实现的具体行为 - 即Apache HttpClient。

看起来它不会在例外(明显)中保留任何详细信息。

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

但如果第一次检查在e.getCause()有什么事......

希望帮助。

+0

记住,它是开源的 - 你总是可以改变它,或者如果你需要作出贡献。 – pstanton 2009-09-29 03:22:47

+0

e.getCause()返回null。 我知道它是开源的,但我是Java的初学者,这是可以为HTTP客户端库创建的最基本的功能:给我错误 – 2009-09-29 05:04:25

+0

很高兴你找到了答案(上面) – pstanton 2009-10-05 00:08:52

相关问题