我有两个 servlet:第一个 servlet 类似于客户端,并创建一个 HttpURLConnection
来调用第二个 servlet。
我想发送一个特殊的错误,格式像一个 JSON 对象,所以我这样调用 sendError 方法:
response.sendError(code, "{json-object}")
但是在第一个 servlet 中,当我使用 getResponseMessage
方法读取错误时,我只得到标准 HTTP 消息,而不是我的 json 对象作为字符串。
如何获取我的 json 字符串?
最佳答案
来自 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.
因此,使用这种方法,您别无选择,只能自己从 HTML 响应中提取消息。 JSoup然而可能是useful在这。
要实现你想要的,你需要自己设置错误代码并编写响应,例如
response.setStatus(code);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
您也可以使用 HttpServletResponse.SC_XXX
constants 之一,而不是 code
为此。
关于java - 将错误消息作为 JSON 对象发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2925176/