我正在使用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错误的消息。这是基本的。
这工作;谢谢。剩下的只是将responseBody InputStream转换为String。 – 2009-09-29 06:07:03
您可以使用EntityUtils.toString(实体)将其转换为字符串。它为你处理字符转换。顺便说一句,JSON错误应该返回200.否则,你无法从浏览器得到响应。 – 2009-09-29 11:15:48
请帮助这里 - http://stackoverflow.com/questions/1490341/how-can-i-get-the-actual-error-behind-httpresponseexception – 2013-12-18 10:51:18