Is it possible in Java to return the 401 Unauthorized response code explicitly

I am working on a web service. I want to return the 401: Unauthorized response to the user for invalid credentials.

How do I manually return this response code?


assuming you are using servlets, you would set the http status to 401 using the setStatus method:


HttpServletResponse info

For error status codes like 401, use the more specific sendError():

httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "your message goes here");

This takes care of everything, it sets the status code and also writes the response.

I've learned the following from both Austin's and Bodgan answers, this may save some minutes for someone else looking for this answer.

For me, the correct answer is Bodgand's:

httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "your message goes here");

The reason is that responses being thrown using the sendError method are catched by the web.xml filters

So if you had specified at your web.xml filter this:


You will only see that error-page when you use the sendError method.

Need Your Help

Browsing through 2 tags on StackOverflow

support tags

I want to browse everything tagged with both [linux] and [performance] on StackOverflow.