Unwanted characters sent when sending XML data via Java Servlets

I am developing a Java web application that simply takes the parameters first_name, middle_nameand last_namethrough the form HTML, and then inserts the data into an XML file and respond to customers' requests.

I have installed Content-Type: text/xml.

Here is my servlet code:

package com.adi.request.xml;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestToXMLServlet extends HttpServlet {

    private String lastName;
    private String firstName;
    private String middleName;

    /* Request Handling... */

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {

        setName(request);  // Initialising the firstName, middleName and lastName
        String xmlDoc = getXML();  // Build and recieve the XML output

        response.setContentType("text/xml");  // TO BE NOTED...

        try(PrintWriter writer = response.getWriter()) {

            writer.print(xmlDoc);  // Printing the XML output
            writer.flush();
        } catch(IOException e) {

            e.printStackTrace();
        }
    }   


    // Setting the firstName, middleName and lastName
    private void setName(HttpServletRequest request) {

        firstName = request.getParameter("first_name");
        lastName = request.getParameter("last_name");
        middleName = request.getParameter("middle_name");
    }

    // Building the XML output
    private String getXML() {
        // The append() methods just adds a \r\n at the end of every line.
        String xmlDoc = append("<?xml version=\"1.0\" encoding=\"utf-8\"?>")+
                        append("<Request>")+
                        append("    <FirstName>"+firstName+"</FirstName>")+
                        append("    <MiddleName>"+middleName+"</MiddleName>")+
                        append("    <LastName>"+lastName+"</LastName>")+
                        append("</Request>");

        return xmlDoc;              
    }

    private String append(String str) {

        return str + "\r\n";
    }
}  

HTML form:

<!DOCTYPE html>
<html>	
<head>
	<title>Request to XML - Servlet</title>
</head>

<body>
		<form method="GET" action="Request.do">
			<label for="first_name">Firstname:</label>
			<input type="text" name="first_name" id="first_name" />
			
			<br>
			
			<label for="middle_name">Middlename</Label>
			<input type="text" name="middle_name" id="middle_name" />
			
			<br>
			
			<label for="last_name">Lastname</Label>
			<input type="text" name="last_name" id="last_name" />
			
			<br>
			
			<input type="submit" name="submit" value="GET" />
		</form>
	</body>
</html>
Run codeHide result

This works great and my browser displays formatted data correctly XML.

The problem is

I wrote a small application jythonthat makes a request HTTP POSTusing raw sockets for the one written above Java Servlet. Although it receives the correct XML formatted data, it also extracts unwanted characters at the beginning and end of the required XML data.

jython:

from java.io import *
from java.net import *
from java.util import *

sock = Socket("localhost", 8080)

ostream = sock.getOutputStream()
writer = PrintWriter(ostream)

params="first_name=Aditya&middle_name=Rameshwarpratap&last_name=Singh"

writer.print("GET /RequestToXML/Request.do?"+params+" HTTP/1.1\r\n")
writer.print("Host: localhost:8080\r\n")
writer.print("Connection: Close\r\n")
writer.print("\r\n")
writer.flush()

istream = sock.getInputStream()
scanner = Scanner(istream)

while(scanner.hasNextLine()):
    print(scanner.nextLine())

istream.close()
ostream.close()
scanner.close()
writer.close()
sock.close()  

:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/xml;charset=ISO-8859-1
Transfer-Encoding: chunked
Date: Thu, 16 Jul 2015 18:46:37 GMT
Connection: close

bc  // What is this?    
<?xml version="1.0" encoding="utf-8"?>
<Request type="POST">
    <FirstName>Aditya</FirstName>
    <MiddleName>Rameshwarpratap</MiddleName>
    <LastName>Singh</LastName>
</Request>

0  // And this?

, :

  • , text/xml?

  • , , , jython- . ?

+4
1

. , :

Transfer-Encoding: chunked

Wikipedia. bc 188 (0xBC = 188). 0 ( , , ).

, , , HTTP 1.1. javadoc doGet():

...

Content-Length ( ServletResponse.setContentLength(int)), , . , .

HTTP 1.1 ( , Transfer-Encoding), Content-Length.

...

, . , , HTTP 1.1.

, ( , HTTP 1.0) HTTP 1.1 ( Java- URLConnection), , .

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    // ...
    String xmlDoc = getXML();
    byte[] content = xmlDoc.getBytes("UTF-8");

    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    response.setContentLengthLong(content.length);
    response.getOutputStream().write(content);
}   

Java EE 7/Servlet 3.1 , , XML , Integer.MAX_VALUE (2 ),

    response.setContentLength((int) content.length);

,

    response.setHeader("Content-Length", String.valueOf(content.length));

, , , (). , try-with-resources. .

. :


, . . . . ? , , .

+4

Source: https://habr.com/ru/post/1598276/


All Articles