42

Using Apache HttpClient 4.1.3 and trying to get the status code from an HttpGet:

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

How do I extract the status code (202, 404, etc.) from the body? Or, if there's another way to do this in 4.1.3, what is it?

Also, I assume a perfect/good HTTP response is an HttpStatus.SC_ACCEPTED but would like confirmation on that as well. Thanks in advance!

Colin 't Hart
  • 7,372
  • 3
  • 28
  • 51
IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756

3 Answers3

80

EDIT:

Try with:

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

The HttpStatus should be 200 ( HttpStatus.SC_OK )

(I've read too fast the problem!)


Try with:

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

This should do the trick!

Enrichman
  • 11,157
  • 11
  • 67
  • 101
5

How about this?

HttpResponse response = client.execute(getRequest);

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

ResponseHandler<String> responseHandler = new BasicResponseHandler();
// Response Body
String responseBody = responseHandler.handleResponse(response);
user1689757
  • 475
  • 5
  • 19
4

I do it like:

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

To get the respose body as a String though by not using a responseHandler I get it first as InputStream:

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

and then convert it to a String (ways how to do that here)

Community
  • 1
  • 1
anastluc
  • 301
  • 2
  • 4