329

I'm wondering if there is an enum type in some standard Java class library that defines symbolic constants for all of the valid HTTP response codes. It should support conversion to/from the corresponding integer values.

I'm debugging some Java code that uses javax.ws.rs.core.Response.Status. It works, but it only defines about half of the valid HTTP response codes.

14 Answers 14

346

I don't think there's one that's complete in the standard Java classes; HttpURLConnection is missing quite a few codes, like HTTP 100/Continue.

There's a complete list in the Apache HttpComponents, though:
org.apache.http.HttpStatus (replaced org.apache.commons.HttpClient.HttpStatus from Apache Http Client, which reached end of life)

8
  • 6
    There's is no such a thing as "complete list", as status codes can be and do get extended. Mar 22, 2012 at 7:14
  • 29
    @JulianReschke I think "complete" here should be taken to mean "conforms to all the codes outlined by the standard". Mar 22, 2012 at 15:19
  • 3
    John: "the standard" does not define "all" the status codes. That's why there is a registry. Mar 23, 2012 at 20:58
  • 2
    iana.org/assignments/http-status-codes/http-status-codes.xml have a big list including the code=100 Mar 27, 2013 at 19:11
  • 2
    @Donal: again, not a good list. What's relevant is the IANA registry. Jul 11, 2013 at 17:12
93

Well, there are static constants of the exact integer values in the HttpURLConnection class

2
  • 15
    thx! this works without any external dependencies. java.net.HttpURLConnection.HTTP_BAD_REQUEST
    – comonad
    Sep 26, 2016 at 9:31
  • 2
    Good that it's part of the standard library but unfortunately it's incomplete - in the 400 range for example it cuts off at 415.
    – tschumann
    May 1, 2020 at 2:46
84

The Interface javax.servlet.http.HttpServletResponse from the servlet API has all the response codes in the form of int constants names SC_<description>. See http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html

3
  • 4
    HttpServletResponse supports the RFC1945 and part of RFC2616 standards, but it's missing all of RFC2518. If you need a complete list, see HttpStatus as I mentioned. Apr 9, 2009 at 3:57
  • 2
    HttpServletResponse is also missing the 418 response code defined in RFC 2324
    – daiscog
    Mar 4, 2016 at 13:31
  • 2
    Using HttpServletResponse in anything that runs outside a servlet is likely to lead to diamond dependency problems due to overlapping classes in different servlet artifacts. Jan 29, 2019 at 11:35
23

If you're using Spring, the 3.x release has what your looking for: http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/http/HttpStatus.html

2
  • 4
    I would like to add that Springs org.springframework.http.HttpStatus (docs.spring.io/spring/docs/current/javadoc-api/org/…) enum, is the only one I could find that provides Java documentation with links to the complete list of status codes and their usage in each enum. If you are already using Spring then this would be the library to use. Jul 7, 2017 at 22:15
  • 2
    It has 100 and 418. Pity that you have to call HttpStatus.XXX.value() to get int.
    – WesternGun
    Mar 14, 2019 at 11:41
13

Here's an enum with status codes and their descriptions that (at time of writing) corresponds to the HTTP status code registry.

Note that the registry might get updated, and that sometimes unofficial status codes are used.

public enum HttpStatusCode {

    //1xx: Informational
    CONTINUE(100, "Continue"),
    SWITCHING_PROTOCOLS(101, "Switching Protocols"),
    PROCESSING(102, "Processing"),
    EARLY_HINTS(103, "Early Hints"),

    //2xx: Success
    OK(200, "OK"),
    CREATED(201, "Created"),
    ACCEPTED(202, "Accepted"),
    NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information"),
    NO_CONTENT(204, "No Content"),
    RESET_CONTENT(205, "Reset Content"),
    PARTIAL_CONTENT(206, "Partial Content"),
    MULTI_STATUS(207, "Multi-Status"),
    ALREADY_REPORTED(208, "Already Reported"),
    IM_USED(226, "IM Used"),

    //3xx: Redirection
    MULTIPLE_CHOICES(300, "Multiple Choice"),
    MOVED_PERMANENTLY(301, "Moved Permanently"),
    FOUND(302, "Found"),
    SEE_OTHER(303, "See Other"),
    NOT_MODIFIED(304, "Not Modified"),
    USE_PROXY(305, "Use Proxy"),
    TEMPORARY_REDIRECT(307, "Temporary Redirect"),
    PERMANENT_REDIRECT(308, "Permanent Redirect"),

    //4xx: Client Error
    BAD_REQUEST(400, "Bad Request"),
    UNAUTHORIZED(401, "Unauthorized"),
    PAYMENT_REQUIRED(402, "Payment Required"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found"),
    METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
    NOT_ACCEPTABLE(406, "Not Acceptable"),
    PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"),
    REQUEST_TIMEOUT(408, "Request Timeout"),
    CONFLICT(409, "Conflict"),
    GONE(410, "Gone"),
    LENGTH_REQUIRED(411, "Length Required"),
    PRECONDITION_FAILED(412, "Precondition Failed"),
    REQUEST_TOO_LONG(413, "Payload Too Large"),
    REQUEST_URI_TOO_LONG(414, "URI Too Long"),
    UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
    REQUESTED_RANGE_NOT_SATISFIABLE(416, "Range Not Satisfiable"),
    EXPECTATION_FAILED(417, "Expectation Failed"),
    MISDIRECTED_REQUEST(421, "Misdirected Request"),
    UNPROCESSABLE_ENTITY(422, "Unprocessable Entity"),
    LOCKED(423, "Locked"),
    FAILED_DEPENDENCY(424, "Failed Dependency"),
    TOO_EARLY(425, "Too Early"),
    UPGRADE_REQUIRED(426, "Upgrade Required"),
    PRECONDITION_REQUIRED(428, "Precondition Required"),
    TOO_MANY_REQUESTS(429, "Too Many Requests"),
    REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large"),
    UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons"),

    //5xx: Server Error
    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    NOT_IMPLEMENTED(501, "Not Implemented"),
    BAD_GATEWAY(502, "Bad Gateway"),
    SERVICE_UNAVAILABLE(503, "Service Unavailable"),
    GATEWAY_TIMEOUT(504, "Gateway Timeout"),
    HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported"),
    VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates"),
    INSUFFICIENT_STORAGE(507, "Insufficient Storage"),
    LOOP_DETECTED(508, "Loop Detected"),
    NOT_EXTENDED(510, "Not Extended"),
    NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required");

    private final int value;
    private final String description;

    HttpStatusCode(int value, String description) {
        this.value = value;
        this.description = description;
    }

    public int getValue() {
        return value;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        return value + " " + description;
    }

    public static HttpStatusCode getByValue(int value) {
        for(HttpStatusCode status : values()) {
            if(status.value == value) return status;
        }
        throw new IllegalArgumentException("Invalid status code: " + value);
    }
}
11

Everyone seems to be ignoring the "enum type" portion of your question.

While there is no canonical source for HTTP Status Codes there is an simple way to add any missing Status constants you need to those provided by javax.ws.rs.core.Response.Status without adding any additional dependencies to your project.

javax.ws.rs.core.Response.Status is just one implementation of the javax.ws.rs.core.Response.StatusType interface. You simply need to create your own implementation enum with definitions for the Status Codes that you want.

Core libraries like Javax, Jersey, etc. are written to the interface StatusType not the implementation Status (or they certainly should be). Since your new Status enum implements StatusType it can be used anyplace you would use a javax.ws.rs.core.Response.Status constant.

Just remember that your own code should also be written to the StatusType interface. This will enable you to use both your own Status Codes along side the "standard" ones.

Here's a gist with a simple implementation with constants defined for the "Informational 1xx" Status Codes: https://gist.github.com/avendasora/a5ed9acf6b1ee709a14a

7

If you are using Netty, you can use:

1
  • unfortunately this is no enum und therefore not usable in case statements(which makes me sad) Jul 21, 2015 at 8:13
6

Use javax.servlet.http.HttpServletResponse class

Example:

javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED //401
javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR //500
3
  • 4
    for client development, it's burdensome to include the entire servlet API just to pick up these codes. Jan 11, 2013 at 20:10
  • 1
    It might be burdensome for some cases but I've found this good answer and I'm writing a servlet-based web app so it's good for me. Feb 3, 2015 at 17:14
  • 2
    A duplicate answer, posted over three years later? Should be deleted.
    – zb226
    Nov 13, 2015 at 13:33
5

1) To get the reason text if you only have the code, you can use:

org.apache.http.impl.EnglishReasonPhraseCatalog.INSTANCE.getReason(httpCode,null)

Where httpCode would be the reason code that you got from the HTTP response.

See https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/impl/EnglishReasonPhraseCatalog.html for details

2) To get the reason code if you only have the text, you can use BasicHttpResponse.

See here for details: https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/message/BasicHttpResponse.html

2

Also check out the Restlet Status class:

http://www.restlet.org/documentation/1.1/api/org/restlet/data/Status.html

1
1

The best provider for http status code constants is likely to be Jetty's org.eclipse.jetty.http.HttpStatus class because:

  • there is a javadoc package in maven which is important if you search for the constant and only know the number -> just open the api docs page and search for the number
  • the constants contain the status code number itself.

Only thing I would improve: put the status code number in front of the text description in order to make auto-completion lookup more convient when you are starting with the code.

1
  • You can't place numbers in front due to Java naming rules but this doesn't matter. A good IDE will auto-complete even if the number shows up later in the name.
    – Gili
    Feb 18, 2022 at 18:45
1

Please see the following enum from the Spring framework which provides all the HTTP response status code

HttpStatus.values()

0

pls try HttpStatus.ACCEPTED.value()

1
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jun 22 at 21:20
-1

Another option is to use HttpStatus class from the Apache commons-httpclient which provides you the various Http statuses as constants.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.