13

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.

3
  • Create your own map <Integer, String>. You can read it from an xml, for example. Commented Nov 18, 2011 at 8:24
  • 2
    I'm pretty sure that a conformant HTTP server MUST send a status code AND a status text. Commented Nov 18, 2011 at 8:34
  • 2
    Yes, I also think that my server has to send code and text, that's why I'm asking :) Commented Nov 18, 2011 at 9:11

3 Answers 3

12

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

Sign up to request clarification or add additional context in comments.

2 Comments

This returns the code number as string, not the text representation.
org.springframework.http.HttpStatus.valueOf(response.statusCode()).getReasonPhrase() will work
6

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>

1 Comment

The "commons-httpclient" is end of life (last release 2007). The new library is org.apache.httpcomponents:httpcore and the method to get the status text is EnglishReasonPhraseCatalog.INSTANCE.getReason(status, null);
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.