【问题标题】:Http Response contains only first character entered into HttpServletResponse.getWriterHttp Response 仅包含输入 HttpServletResponse.getWriter 的第一个字符
【发布时间】:2019-05-04 12:30:28
【问题描述】:

我目前正在编写一个允许用户编写自定义休息端点的 servlet。端点产生一个RestResponse 对象,我试图将其转换为最终的HTTPServletResponse 对象。 RestResponse 包含一个代表响应正文的org.json.simple.JSONObject。我现在需要将此对象放入 HTTP 响应的正文中。

我的想法是使用HTTPServletResponsePrintWriter,根据调试器的说法,整个JSONObject 应该在PrintWriterCharBuffer 中结束,但是在最终的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


    【解决方案1】:

    所以我的问题是我以某种方式将http.setContentlength(variable) 设置为变量意外为 1,因此显然正文将只包含第一个字符。

    【讨论】:

      猜你喜欢
      • 2021-01-05
      • 2013-04-25
      • 1970-01-01
      • 2013-07-16
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多