Java 将错误消息作为 JSON 对象发送
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2925176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send error message as JSON object
提问by pAkY88
I have two servlet: first servlet is similar to a client and creates an HttpURLConnection
to call the second servlet.
我有两个 servlet:第一个 servlet 类似于客户端,并创建一个HttpURLConnection
来调用第二个 servlet。
I would like send a special error, formatted like a JSON object, so I call sendError method in this way:
我想发送一个特殊的错误,格式像一个 JSON 对象,所以我以这种方式调用 sendError 方法:
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.
但是在第一个 servlet 中,当我使用getResponseMessage
方法读取错误时,我只得到标准的 HTTP 消息,而不是我的 json 对象作为字符串。
How I can get my json string?
我怎样才能得到我的 json 字符串?
采纳答案by BalusC
From the HttpServletResponse#sendError()
javadoc:
从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 格式的服务器错误页面,将内容类型设置为“text/html”,不修改 cookie 和其他标题。如果已为与传入的状态代码相对应的 Web 应用程序进行了错误页面声明,则它将优先于建议的 msg 参数返回。
So with this approach you have no other option than extracting the message from the HTML response yourself. JSoupmay however be usefulin this.
因此,使用这种方法,您除了自己从 HTML 响应中提取消息之外别无选择。然而,JSoup在这方面可能很有用。
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
constantsfor this.
code
顺便说一下,您也可以为此使用其中一个HttpServletResponse.SC_XXX
常量。