2009-09-29 26 views
8

私は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エラーのメッセージを取得する簡単な方法が必要です。これは初心者です。

答えて

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にスラップすることだけでした。 –

+1

EntityUtils.toString(エンティティ)を使用して文字列に変換できます。それはあなたのための文字変換を処理します。 BTW、JSONエラーは200と返される必要があります。それ以外の場合は、ブラウザから応答を取得することはできません。 –

+0

ここをクリックしてください - http://stackoverflow.com/questions/1490341/how-can-i-get-the-actual-error-behind-httpresponseexception –

1

responseBodyは、値の割り当て中に例外がスローされた場合、常にnullになります。

それ以外にも実装の具体的な動作、つまりApache HttpClientがあります。

例外の詳細情報(明らかに)は維持されていないようです。

私はHttpClientのソースコードをロードしてデバッグします。

しかしe.getCause()...助け

希望に何があるかどう最初のチェック。

+0

は、それがオープンソースだ、覚えている - あなたは常にそれを変更したり、必要であれば貢献できます。 – pstanton

+0

e.getCause()はnullを返します。 私はそれがオープンソースだと知っていますが、私はJavaの初心者です。これはHTTPクライアントライブラリ用にイメージングすることができる最も基本的な機能です: –

+0

答えを見つけてうれしいです。 – pstanton

関連する問題