2009-09-29 11 views
8

Sto utilizzando Apache HttpComponents Client su POST su un server che restituisce JSON. Il problema è che se il server restituisce un errore 400, sembra che non abbia modo di dire quale sia l'errore di Java (ha dovuto ricorrere a uno sniffer di pacchetti fino ad ora - ridicolo). Ecco il codice:Come posso ottenere l'errore reale dietro 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 "" 
} 

Cosa sto facendo male? Ci deve essere un modo semplice per ottenere il messaggio di un errore 400. Questo è elementare.

risposta

12

Perché si utilizza BasicResponseHandler()? Il gestore lo sta facendo per te. Questo gestore è solo un esempio e non dovrebbe essere usato nel codice reale.

È necessario scrivere il proprio gestore o eseguire la chiamata senza un gestore.

Per esempio,

 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

Questo ha funzionato; Grazie. Tutto ciò che restava da fare era di borbottare la rispostaBody InputStream in una stringa. –

+1

È possibile utilizzare EntityUtils.toString (entità) per convertirlo in stringa. Gestisce la conversione del codice per te. BTW, l'errore JSON dovrebbe essere restituito con 200. Altrimenti, non è possibile ottenere risposta dal browser. –

+0

per favore aiuto qui - http://stackoverflow.com/questions/1490341/how-can-i-get-the-actual-error-behind-httpresponseexception –

1

responseBody sarà sempre nullo se viene generata un'eccezione durante l'assegnazione di un valore.

oltre a ciò è un comportamento specifico dell'implementazione, ad esempio Apache HttpClient.

Sembra che non mantenga alcuna delle informazioni dettagliate nell'eccezione (ovviamente).

Vorrei caricare il codice sorgente per HttpClient e debuggarlo.

ma prima verifica se c'è qualcosa nella e.getCause() ...

speranza che aiuta.

+0

ricordate, è open source - è sempre possibile modificarlo o contribuire se è necessario. – pstanton

+0

e.getCause() restituisce null. Io so che è open source, ma io sono un principiante di Java e questa è la funzionalità più semplice che si può immaginare per una libreria client HTTP: dammi l'errore –

+0

contento di aver trovato una risposta (sopra) – pstanton

Problemi correlati