I need to read XML document submitted to doPost() method ( I do not want to upload it, just read in and pass for further processing). Here is a general code that I use for now to see if file been received.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        ServletInputStream sis = null;
        try {
            sis = request.getInputStream();
        }
        catch (IllegalStateException e) {
            e.printStackTrace();
        }
        if (sis != null) {
            print(sis);
            sis.close();
        }
    }

    private void print(ServletInputStream sis){
        java.io.BufferedReader br = null;
        try{
            br = new java.io.BufferedReader(new java.io.InputStreamReader(sis));

            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }

            br.close();
            System.out.println(sb.toString());
        }
        catch(IOException e){
            e.printStackTrace();
        }
    }

To test this I use curl utility to pass file to url as

curl URL --data-binary @FILENAME -H 'Content-type: application/atom+xml;type=entry'

However content of the file is not printed, only new line is added which means process get to this sb.append(line + "\n"); command.

Any advice is welcome.

Problem solved with use of Commons IO API, time for more XML n00bing

private void readFileAsString(String filePath) throws
java.io.IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new
FileReader(filePath));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        System.out.println(fileData.toString());
    }

PS: String in method parameter received need to be obviously replaced by InputStream, you got the idea hope...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.