Search code examples
javaservletsprintwriter

Http Response contains only first character entered into HttpServletResponse.getWriter


Im currently writing a servlet that should allow the user to write custom rest endpoints. The endpoints produce a RestResponse object which i am trying to convert into the final HTTPServletResponse Object. The RestResponse contains a org.json.simple.JSONObject representing the Response Body. I now need to get this Object into the Body of of the HTTP Response.

My Idea is to use the PrintWriter of the HTTPServletResponse, According to the Debugger the entire JSONObject ends Up in the CharBuffer of the PrintWriter as it should, however in the final HTTP Response Body inside my Browser there is only the first character.

rest is my RestResponse object and http is my HTTPServletResponse Object (coming unchanged since handed into the doGet Method of the servlet)

I tried to use various different methods like:

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();
}

and so on, everything gives the same result

I've been debugging this for several hours now and i still didn't figure out whats wrong, does anybody have an idea?

Cheers


Solution

  • So my issue was that somehow i set http.setContentlength(variable) where variable accidentally was 1, therefor apparently the body will only contain the first character.