简体   繁体   中英

How to get the HTTP method of a REST request

In case of an exception in my Java REST application I would like to log various information on causing HTTP request.

I can obtain the URI of the request and the HTTP headers via context injection

@Context
private UriInfo uriInfo;

@Context
private HttpHeaders headers;

But how can I obtain the HTTP method (GET, PUT, ...)?

I use Jersey. Don't know if this applies for you but ... :

import javax.servlet.http.HttpServletRequest;    

@Context final HttpServletRequest request

The Request class has the method getMethod() . It returns the used HTTP method.

You are usually limiting the rest methods to one http method

 @GET
 @Produces("text/plain")
  public String getClichedMessage() {
    // Return some cliched textual content
    return "Hello World";
 }

Jersey is irrelevant (following the most upvoted answer.)

HttpServletRequest class of Java Servlet API has getMethod() method that returns the name of the HTTP method ( GET, POST, PUT , etc).

But you do not always need it. For example, if you are in servlet, you have doGet, doPost methods.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   //method is POST
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //method is GET }

But you do need it, for example, in the filter:

public void doFilter(ServletRequest request, ServletResponse response, 
          FilterChain chain) throws ServletException, IOException {

     String method = ((HttpServletRequest) request).getMethod();

} 

Speaking of the REST, different REST frameworks may provides various ways to obtain the HttpServletRequest object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM