私はApache HttpComponents Clientを使用してJSONを返すサーバーにPOSTします。問題は、サーバーが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にスラップすることだけでした。 –
EntityUtils.toString(エンティティ)を使用して文字列に変換できます。それはあなたのための文字変換を処理します。 BTW、JSONエラーは200と返される必要があります。それ以外の場合は、ブラウザから応答を取得することはできません。 –
ここをクリックしてください - http://stackoverflow.com/questions/1490341/how-can-i-get-the-actual-error-behind-httpresponseexception –