Reputation: 4183
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, ...)?
Upvotes: 10
Views: 16419
Reputation: 6137
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.
Upvotes: 1
Reputation: 3156
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.
Upvotes: 20
Reputation: 5913
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";
}
Upvotes: 0