2012-06-06 13 views
36

Utilizzo di Apache HttpClient 4.1.3 e cercando di ottenere il codice di stato da un HttpGet:HttpClient ottenere il codice di stato

HttpClient client = new DefaultHttpClient(); 
HttpGet response = new HttpGet("http://www.example.com"); 
ResponseHandler<String> handler = new BasicResponseHandler(); 
String body = client.execute(response, handler); 

Come posso estrarre il codice di stato (202, 404, ecc) dal body ? Oppure, se c'è un altro modo per farlo in 4.1.3, che cos'è?

Inoltre, presumo che una risposta HTTP perfetta/buona sia una HttpStatus.SC_ACCEPTED ma vorrei confermarla anche su questo. Grazie in anticipo!

risposta

69

EDIT:

Prova con:

HttpResponse httpResp = client.execute(response); 
int code = httpResp.getStatusLine().getStatusCode(); 

Il HttpStatus dovrebbe essere 200 (HttpStatus.SC_OK)


(ho letto troppo in fretta il problema!)

Prova con:

GetMethod getMethod = new GetMethod("http://www.example.com"); 
int res = client.executeMethod(getMethod); 

Questo dovrebbe fare il trucco!

+0

Enrichman - grazie ma non sembra che 'GetMethod' esista in 4.1.3 - qualche idea? – IAmYourFaja

4

lo faccio come:

HttpResponse response = client.execute(httppost); 
int status = response.getStatusLine().getStatusCode(); 

per ottenere il corpo respose come String se non usando un responseHandler ho capito prima come InputStream:

InputStream is = response.getEntity().getContent(); 

e quindi convertirlo in un Stringa (modi come farlo here)

5

Che ne dici di questo?

HttpResponse response = client.execute(getRequest); 

// Status Code 
int statusCode = response.getStatusLine().getStatusCode(); 

ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
// Response Body 
String responseBody = responseHandler.handleResponse(response); 
Problemi correlati