将错误消息作为JSON对象发送 [英] Send error message as JSON object
问题描述
我有两个servlet:第一个servlet类似于一个客户端,并创建一个 HttpURLConnection
来调用第二个servlet。
I have two servlet: first servlet is similar to a client and creates an HttpURLConnection
to call the second servlet.
我想发送一个特殊错误,格式化为JSON对象,所以我用这种方式调用sendError方法:
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}")
但是在我的第一个servlet中使用读取错误getResponseMessage
方法我只是获取标准HTTP消息而不是我的json对象作为字符串。
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.
我如何可以得到我的json字符串吗?
How I can get my json string?
推荐答案
来自 HttpServletResponse#sendError()
javadoc :
From the HttpServletResponse#sendError()
javadoc:
服务器默认创建的响应看起来像HTML格式的服务器错误页面包含指定的消息,se将内容类型设置为text / html,不改变cookie和其他标题。如果对与传入的状态代码相对应的Web应用程序进行了错误页面声明,则将优先于建议的msg参数进行服务。
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 可能有用。
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);
而不是代码
你可以顺便说一下还可以使用 HttpServletResponse.SC_XXX
常数。
Instead of code
you could by the way also use one of the HttpServletResponse.SC_XXX
constants for this.
这篇关于将错误消息作为JSON对象发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!