开发者

Setting a string in a body of httpResponse

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?


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


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 :)


If that's meant to be XML, Word has already spoiled things for you by changing the attribute quote symbol to instead of ".

It is worth having a look at JAXP if you want to generate XML using Java. Writing strings with < etc. in them won't scale and you'll run into problems with encodings of non-ASCII characters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜