91

I'm using the org.apache.http.HttpResponse class in my Java application, and I need to be able to get the HTTP status code. If I used .toString() on it, I can see the HTTP status code in there. Is there any other function that I can just get the HTTP status code as either an int or String?

Thanks a bunch!

Chiggins
  • 8,197
  • 22
  • 56
  • 81

4 Answers4

139

Use HttpResponse.getStatusLine(), which returns a StatusLine object containing the status code, protocol version and "reason".

matt b
  • 138,234
  • 66
  • 282
  • 345
72

I have used httpResponse.getStatusLine().getStatusCode() and have found this to reliably return the integer http status code.

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
user1735872
  • 729
  • 5
  • 3
38
httpResponse.getStatusLine().getStatusCode()
Peter O.
  • 32,158
  • 14
  • 82
  • 96
bentobox
  • 3,948
  • 2
  • 16
  • 10
3

A example will be as below,

        final String enhancementPayload ="sunil kumar";
        HttpPost submitFormReq = new HttpPost("https://bgl-ast/rest/service/form/form-data");
        StringEntity enhancementJson = new StringEntity(enhancementPayload);
        submitFormReq.setEntity(enhancementJson);
        submitFormReq.setHeader("Content-Type", "application/xml");

        HttpResponse response = httpClient.execute( submitFormReq );
        String result = EntityUtils.toString(response.getEntity());
        System.out.println("result "+result);
        assertEquals(200, response.getStatusLine().getStatusCode());
Linus
  • 880
  • 13
  • 25