Reputation: 17883
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?
Upvotes: 12
Views: 35631
Reputation: 6419
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:
<error-page>
<error-code>401</error-code>
<location>/errors/401.jsp</location>
</error-page>
You will only see that error-page when you use the sendError
method.
Upvotes: 0
Reputation: 8283
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.
Upvotes: 20
Reputation: 33544
assuming you are using servlets, you would set the http status to 401 using the setStatus
method:
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
Upvotes: 17