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.
Questo ha funzionato; Grazie. Tutto ciò che restava da fare era di borbottare la rispostaBody InputStream in una stringa. –
È 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. –
per favore aiuto qui - http://stackoverflow.com/questions/1490341/how-can-i-get-the-actual-error-behind-httpresponseexception –