What's the proper way to set the Location header for an HTTP 201 response in a Java Servlet application

前端 未结 5 1492
醉梦人生
醉梦人生 2021-01-31 02:49

Consider the following code sending an HTTP 201 \"Created\" response to the client:

    String url = \"/app/things?id=42\"; // example
    response.setStatus(Htt         


        
5条回答
  •  离开以前
    2021-01-31 03:20

    Decided to go with Julian Reschke's advice and violate the spec! At least I added the following comment:

            /* Note: strictly speaking (per section 14.30 of RFC 2616), the Location header 
             * requires an *absolute URI*. However, in practice, many web 
             * applications send an *absolute path* instead. This is interoperable, 
             * that is, works in popular web browsers  (according to 
             * http://en.wikipedia.org/wiki/HTTP_location).
             * 
             * As the information required to set the Location header to an absolute URI
             * is not generally available to a Servlet, we go with the flow and send
             * an absolute path instead (in violation of RFC 2616).
             * 
             * There is an issue filed with Hypertext Transfer Protocol Bis (httpbis) 
             * working group to resolve this problem here:
             * http://trac.tools.ietf.org/wg/httpbis/trac/ticket/185
             */
            response.setHeader("Location", url);
    

    The reason I don't want to send the absolute URI myself is because I have seen problems with this when behind load-balancers and other production infrastructure. Although in dev mode "http://localhost:8080/foo" tends to work fine :))

    Will accept Julian's answer now ...

提交回复
热议问题