Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a string in a body of httpResponse

Tags:

java

servlets

I need help. In my current development one of the requirements says:

The server will return 200-OK as a response(httpresponse).

If the panelist is verified then as a result, the server must also return the panelist id of this panelist.

The server will place the panelist id inside the body of the 200-OK response in the following way:

<tdcp>  <cmd>     <ack cmd=”Init”>        <panelistid>3849303</panelistid>     </ack>  </cmd> 

Now I am able to put the httpresponse as

httpServletResponse.setStatus(HttpServletResponse.SC_OK); 

And I can put

String responseToClient= "<tdcp><cmd><ack cmd=”Init”><panelistid>3849303</panelistid></ack></cmd></tdcp>";

Now what does putting the above xml inside the body of 200-OK response mean and how can it be achieved?

like image 892
vibhas Avatar asked Oct 05 '11 08:10

vibhas


2 Answers

You can write the XML directly to the response as follows:

This example uses a ServletResponse.getWriter(), which is a PrintWriter to write a String to the response.

String responseToClient= "<tdcp><cmd><ack cmd=”Init”><panelistid>3849303</panelistid></ack></cmd></tdcp>";  httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter().write(responseToClient); httpServletResponse.getWriter().flush(); 
like image 126
Buhake Sindi Avatar answered Sep 19 '22 08:09

Buhake Sindi


You simply need to get the output stream (or output writer) of the servlet response, and write to that. See ServletResponse.getOutputStream() and ServletResponse.getWriter() for more details.

(Or simply read any servlet tutorial - without the ability to include data in response bodies, servlets would be pretty useless :)

like image 43
Jon Skeet Avatar answered Sep 22 '22 08:09

Jon Skeet