簡體   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