XML in servlet response
Question posted by: mkwg
(Newbie)
on
August 21st, 2008 08:11 PM
Hi,
I wonder if anyone can help with this question.
I have a test servlet that simply echoes back XML text that is sent to it, with UTF-8 encoding. Here's the servlet code:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
ServletInputStream sis = request.getInputStream();
ServletOutputStream sos = response.getOutputStream();
//File file = new File("C:/echo.xml");
//FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int i = 0;
while((i=sis.read(buf))!=-1) {
sos.write(buf, 0, i);
//fos.write(buf, 0, i);
}
sis.close();
sos.close();
//fos.close();
}
The XML text that arrives in the request has the header:
<?xml version="1.0" encoding="UTF-8"?>
The file output (commented out in the code above) shows the header:
<?xml version="1.0" encoding="UTF-8"?>
But the XML text that appears in the response has the header:
<?xml version="1.0"?>
The response header contains, as expected:
Content-Type: text/xml;charset=UTF-8
I'm assuming that this is some behavior of the ServletResponse interface.
If so:
- is this documented?
- is there any way to control/prevent it, so that the XML text in the response shows the same header?
Many thanks for any help/advice with this.
MKWG
1
Answer Posted
That sounds weird. As far as I know the servlet response data section contains exactly the bytes you write to it.
Are you using a browser to access the servlet ?
Are you 100% sure that the browser is not pretty printing the XML
and the removing the enconding attribute (it is redundant since UTF-8 is the standard encoding).
Try using netcat, curl or wget to access the servlet. This way you can be sure that nothing alters the data
/Christoffer
|
|
|
What is Bytes?
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 197,047 network members.
|