32

I have two servlet: first servlet is similar to a client and creates an HttpURLConnection to call the second servlet.

I would like send a special error, formatted like a JSON object, so I call sendError method in this way:

response.sendError(code, "{json-object}")

But in the first servlet when I read error with getResponseMessage method I just get standard HTTP message and not my json object as a string.

How I can get my json string?

1 Answer 1

63

From the HttpServletResponse#sendError() javadoc:

The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html", leaving cookies and other headers unmodified. If an error-page declaration has been made for the web application corresponding to the status code passed in, it will be served back in preference to the suggested msg parameter.

So with this approach you have no other option than extracting the message from the HTML response yourself. JSoup may however be useful in this.

To achieve what you want, you need to set the error code and write the response yourself, e.g.

response.setStatus(code);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

Instead of code you could by the way also use one of the HttpServletResponse.SC_XXX constants for this.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I had a doubt about this and I posted the question, your suggest is only way to get json string without to find it in html code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.