How to convert HTTP status code into text in Java?

2019-06-15 15:02发布

问题:

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.

回答1:

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>


回答2:

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



标签: java http