【发布时间】:2019-05-04 12:30:28
【问题描述】:
我目前正在编写一个允许用户编写自定义休息端点的 servlet。端点产生一个RestResponse 对象,我试图将其转换为最终的HTTPServletResponse 对象。
RestResponse 包含一个代表响应正文的org.json.simple.JSONObject。我现在需要将此对象放入 HTTP 响应的正文中。
我的想法是使用HTTPServletResponse 的PrintWriter,根据调试器的说法,整个JSONObject 应该在PrintWriter 的CharBuffer 中结束,但是在最终的HTTP 响应正文中在我的浏览器中只有第一个字符。
rest 是我的 RestResponse 对象,http 是我的 HTTPServletResponse 对象(自从交给 servlet 的 doGet 方法后保持不变)
我尝试使用各种不同的方法,例如:
if (rest.hasBody()) {
//TODO this somehow fails to write a valid JSON String to the HTTP Body
PrintWriter writer = http.getWriter();
rest.getBody().writeJSONString(writer);
//Here the proper json string ends in the buffer of the writer
writer.flush();
writer.close();
}
if (rest.hasBody()) {
//TODO this somehow fails to write a valid JSON String to the HTTP Body
PrintWriter writer = http.getWriter();
writer.write(rest.getBody.toJSONString());
//Here the proper json string ends in the buffer of the writer
writer.flush();
writer.close();
}
if (rest.hasBody()) {
//TODO this somehow fails to write a valid JSON String to the HTTP Body
PrintWriter writer = http.getWriter();
writer.append(rest.getBody.toJSONString());
//Here the proper json string ends in the buffer of the writer
writer.flush();
writer.close();
}
以此类推,一切都给出相同的结果
我已经调试了好几个小时了,但我仍然没有弄清楚哪里出了问题,有人知道吗?
干杯
【问题讨论】:
标签: java servlets printwriter