Question
How can I get the HTTP status code from org.apache.http.HttpResponse in my Java application? Is there a function that directly returns this as an integer or String?
HttpResponse response;
int statusCode = response.getStatusLine().getStatusCode();
String statusMessage = response.getStatusLine().getReasonPhrase();
Answer
To fetch the HTTP status code from the `org.apache.http.HttpResponse` class in Java, you can utilize the `getStatusLine()` method, which provides access to the status line of the response, encompassing both the status code and the reason phrase.
HttpResponse response;
int statusCode = response.getStatusLine().getStatusCode();
String statusMessage = response.getStatusLine().getReasonPhrase();
System.out.println("HTTP Status Code: " + statusCode);
System.out.println("Status Message: " + statusMessage);
Causes
- The method `toString()` provides a verbose representation of the HTTP response, but it's inefficient for simply retrieving the status code.
- Developers may overlook more straightforward methods that directly yield the status code.
Solutions
- Use `getStatusLine().getStatusCode()` to directly retrieve the status code as an integer.
- Alternatively, use `getStatusLine().getReasonPhrase()` to get a string representation of the status message.
Common Mistakes
Mistake: Using the toString() method to extract the status code, which may lead to performance issues.
Solution: Utilize the designated getter methods like getStatusLine() for better performance.
Mistake: Assuming the status code could be obtained directly from the HttpResponse object without accessing the StatusLine.
Solution: Always retrieve the status code through getStatusLine().getStatusCode().
Helpers
- org.apache.http.HttpResponse
- HTTP status code Java
- get HTTP code Java
- HttpResponse getStatusLine
- retrieve HTTP status code Java