繁体   English   中英

如何获取 REST 请求的 HTTP 方法

[英]How to get the HTTP method of a REST request

如果我的 Java REST 应用程序出现异常,我想记录有关引起 HTTP 请求的各种信息。

我可以通过上下文注入获取请求的 URI 和 HTTP 标头

@Context
private UriInfo uriInfo;

@Context
private HttpHeaders headers;

但是如何获取 HTTP 方法(GET、PUT、...)?

我用泽西岛。 不知道这是否适用于您,但是...:

import javax.servlet.http.HttpServletRequest;    

@Context final HttpServletRequest request

Request类具有方法getMethod() 它返回使用的HTTP方法。

您通常将其余方法限制为一个http方法

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

泽西岛无关紧要(遵循最受好评的答案。)

Java Servlet API 的 HttpServletRequest 类具有返回 HTTP 方法名称( GET, POST, PUT等)的getMethod()方法。

但你并不总是需要它。 例如,如果您在 servlet 中,则有 doGet、doPost 方法。

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

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //方法是 GET }

但是你确实需要它,例如,在过滤器中:

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

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

} 

说到REST,不同的REST框架可能会提供多种获取HttpServletRequest对象的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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