Get HTTP code from org.apache.http.HttpResponse

JavaApacheHttpresponse

Java Problem Overview


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!

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

httpResponse.getStatusLine().getStatusCode()

Solution 4 - Java

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());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChigginsView Question on Stackoverflow
Solution 1 - Javamatt bView Answer on Stackoverflow
Solution 2 - Javauser1735872View Answer on Stackoverflow
Solution 3 - JavabentoboxView Answer on Stackoverflow
Solution 4 - JavaLinusView Answer on Stackoverflow