Tôi đang sử dụng Apache HttpComponents Client để POST tới máy chủ trả về JSON. Vấn đề là nếu máy chủ trả về một lỗi 400, tôi dường như không có cách nào để nói những gì lỗi là từ Java (đã phải nghỉ mát đến một gói sniffer cho đến nay - vô lý). Đây là mã:Làm cách nào để có được lỗi thực tế đằng sau 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 ""
}
Tôi đang làm gì sai? Phải có một cách dễ dàng để nhận được thông báo lỗi 400. Đây là tiểu học.
cảm ơn. Tất cả những gì còn lại là để slurp responseBody InputStream thành một String. –
Bạn có thể sử dụng EntityUtils.toString (thực thể) để chuyển đổi nó thành chuỗi. Nó xử lý chuyển đổi char cho bạn. BTW, lỗi JSON phải được trả lại bằng 200. Nếu không, bạn không thể nhận phản hồi từ trình duyệt. –
vui lòng trợ giúp tại đây - http://stackoverflow.com/questions/1490341/how-can-i-get-the-actual-error-behind-httpresponseexception –