我正在使用Apache HttpComponents Client來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 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錯誤的消息.這是基本的.