XML in servlet response

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mkwg
    New Member
    • Aug 2008
    • 1

    XML in servlet response

    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(HttpServ letRequest request,
    HttpServletResp onse response)
    throws ServletExceptio n, IOException {
    response.setCon tentType("text/xml");
    response.setCha racterEncoding( "UTF-8");
    ServletInputStr eam sis = request.getInpu tStream();
    ServletOutputSt ream sos = response.getOut putStream();
    //File file = new File("C:/echo.xml");
    //FileOutputStrea m fos = new FileOutputStrea m(file);
    byte[] buf = new byte[1024];
    int i = 0;
    while((i=sis.re ad(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
  • cdbruun
    New Member
    • Aug 2008
    • 1

    #2
    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

    Comment

    Working...