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?
From the
HttpServletResponse#sendError()
javadoc: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.
Instead of
code
you could by the way also use one of theHttpServletResponse.SC_XXX
constants for this.