Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HTTP status code into text in Java?

Tags:

java

http

How can I convert HTTP status code to its text representation, in Java? I mean are there any existing implementations of such a conversion. The best I've found so far is java.ws.rs.core.Response.Status#fromStatusCode(), which converts only a limited subset of all statuses.

like image 722
yegor256 Avatar asked Nov 18 '11 08:11

yegor256


People also ask

How do you read a response body in Java?

To get the response body as a string we can use the EntityUtils. toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.

What is HTTP status code in Java?

HTTP status codes are part of the status-line of a HTTP response. These 3-digit integer codes indicate the result of the servers attempt to satisfy the request. The first digit of the status-code is used to categorize the response: 1xx: Informal. 2xx: Success, the request has been understood and accepted.

How do I retrieve my HTTP status code?

In the main window of the program, enter your website homepage URL and click on the 'Start' button. As soon as crawling is complete, you will have all status codes in the corresponding table column. Pages with the 4xx and 5xx HTTP status codes will be gathered into special issue reports.

What is Httpstatus OK?

The HTTP Status 200 (OK) status code indicates that the request has been processed successfully on the server. The response payload depends on the HTTP method which was selected for the request.


3 Answers

If you are working with Spring, or are okay with importing Spring Web, then this would do it:

First import it:

import org.springframework.http.HttpStatus;

Then use it like:

int statusCode = 502;
String message = HttpStatus.valueOf(statusCode).getReasonPhrase();
like image 122
misteeque Avatar answered Sep 24 '22 18:09

misteeque


Apache HttpComponents has an (old-style) enum class which does this:

http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/HttpStatus.html

You can call itsgetStatusText method with an enum instance as the argument to get the text representation of a status code.

Maven dependency is:

<dependency>
  <groupId>commons-httpclient</groupId>
  <artifactId>commons-httpclient</artifactId>
  <version>3.1</version>
</dependency>
like image 39
MartinZ Avatar answered Sep 23 '22 18:09

MartinZ


If you're happy to import Spring web, org.springframework.http.HttpStatus.valueOf(int).name() should do, if you don't mind underscores.

like image 37
artbristol Avatar answered Sep 21 '22 18:09

artbristol