java - 将错误消息作为 JSON 对象发送

标签 java json http servlets

我有两个 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/

相关文章:

java - 在 hibernate 中从 postgresql 查询 JSON 数组会抛出 JDBC 类型没有方言映射 : 1111

python - 代理服务器不发送所有数据python

http - 此响应是否正确编码?

python - 我收到错误 400 : Bad Request on custom Heroku domain, 但在 foo.herokuapp.com 上工作正常

java - 计数器不工作

java - DataOutputStream 空指针异常

java - 限制 Apache HttpClient 中每秒的连接数

java - 我的 brainfuck 解析器代码有什么问题?

jquery - 将更多对象数组添加到本地存储键中

javascript - JSON Highcharts绘制多条线