Reading client-posted data via Tomcat servlet


I'm doing some simple client/servlet communication using Tomcat, using POST's via an HttpURLConnection.

I'm seeing my data at the servlet side via getInputStream(), but I can't decode it to a String, even by using InputStreamReader (which is supposed to do that). If I send a 5 character String, at the servlet I see "^@^@^@^@^@". I've tried constructing a String from a byte[], but it doesn't decode, either.

I've tried writing the data as text with PrintWriter on the client side, and then reading text on the servlet side with getReader(), but getReader() returns null, even though a call to HttpServletRequest's getContentLength() returns non-zero (and shows the correct number of characters and/or bytes).

Reading the docs and api's leads me to believe this should be very straightforward, but it's just not working.  I'm beginning to wonder if the problem is within Tomcat itself.

Any thoughts would be greatly appreciated!!!

Thanks in advance!

- Dean

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Please post the shortest extracts you can from both ends
dzarrasAuthor Commented:
Client side:

 URL location = null;
        URLConnection con = null;

            System.err.println("URL is [" + url + "]");
            location = new URL(url);

            con = location.openConnection();

            if (con instanceof HttpURLConnection){
                HttpURLConnection httpCon = (HttpURLConnection) con;



            DataOutputStream out = new DataOutputStream(con.getOutputStream());

        System.err.println("POST is [" + content + "]");

Server side:

(From within the service method, where I have an HttpServletRequest instance 'request', I call this method using request.getContentLength() and request.getInputStream())

 private String readStringFromDataOutputStream(int length,
                                                  ServletInputStream instream) throws IOException

        DataInputStream dis = new DataInputStream(instream);

        byte[] raw = new byte[length];,0,length);
        String body = new String(raw);

       return body;

In the case of sending a simple string to the servlet "ABCDE", the method above returns the string "^@^@^@^@^@".

My real intention is to send a very large string to the servlet.

Thanks for your interest -- I look forward to further feedback.


- Dean
You need to do this as well:

con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");



should be

String encoded = URLEncoder.encode(content, "UTF8");

You need to decode it on the other side too.

There is no apparent need to use DataXStream if you're just writing Strings

Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

dzarrasAuthor Commented:

I tried the above but it made no difference.

The contentType (as returned by request.getContentType() was already returning the value you show above anyway, but setting it in the Connection from the client side did not make a difference.    

Also, I agree that I shouldn't have to use DataInput/Output/Stream, which would obviate the need to call writeBytes(), as you suggest above.

My test string "ABCDE" doesn't encode to anything different (unlike a string with spaces or '&', etc), so the encoding shouldn't (and doesn't) make a difference in this case.

>>My test string "ABCDE" doesn't encode to anything different

No - it won't. But you might need to encode it later.

Can you post your new code altered to get rid of DataXStreams. Also use Readers for Strings
dzarrasAuthor Commented:

private void writeStringAsText(OutputStream outputStream, String content) throws UnsupportedEncodingException
        PrintWriter printer = new PrintWriter(outputStream);

        String encoded = URLEncoder.encode(content,"UTF-8");

        System.err.println("Cotent is [" + content + "], encoded = [" + encoded + "]");


Here's the reader, trying to get Strings one line at a time:

private String readStringFromReader(BufferedReader reader)
       int computedLen = 0;
       int linesRead = 0;

        StringBuffer sBuf = new StringBuffer();
            String inputStr = reader.readLine();
            if (inputStr != null){
                String line = URLDecoder.decode(inputStr,"UTF-8");
                toLog(LOG_LEVEL_MANDATORY,"First line is [" + line + "]");

                while (line != null){
                    computedLen += line.length();
                    inputStr = reader.readLine();
                    if (inputStr != null){
                        line = URLDecoder.decode(inputStr,"UTF-8");
                        line = null;
                toLog(LOG_LEVEL_MANDATORY,"Never got first string");
        catch (Exception e){

        String theString = sBuf.toString();
        String results = "sBuf = [" + theString + "] linesRead = " + linesRead + " computed = " + computedLen;


        return theString;

The above method never gets a String from the reader, (ie, linesRead is 0).

The reader, btw, is simply HttpServletRequest's getReader().

How do you get the reader in the first place?
dzarrasAuthor Commented:
From the implementation of HttpServlet's doPost method, which is called by the container upon receiving a POST:

protected void doPost(HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse)
            throws ServletException, IOException

       BufferedReader reader = httpServletRequest.getReader();

Mick BarryJava DeveloperCommented:
I don't see any need to encode/decode the string.

Use println instead of print on the server.
Mick BarryJava DeveloperCommented:
I'm assuming you are reading multiple lines because the source string may contain eol chars. The code to read the string can be simplified as follows.

                while ((line = reader.readLine()) != null){
                    computedLen += line.length();
dzarrasAuthor Commented:
Strange news...

Yesterday the "problem" disappeared, and making the suggested changes above did not cause the problem to disppear, or reappear if I removed them.     In other words, using the very straightforward approach of writing un-encoded text to the servlet, and reading it via getReader(), worked perfectly.

However today, it is failing again.   Clearly something's going on at Tomcat's level (this is version 4.1.18 -- I plan on upgrading to 4.1.29 today).

What I have learned is that the returned by HttpServletRequest's getReader() method is returning false when I call ready().   The reader's ready() should return true if the reader is capable of returning anything.

I'm exploring the above further.
dzarrasAuthor Commented:
So what this boils down to so far, is

request.getContentLength() returns non-zero (indicating content has been received by the servlet), but request.getReader().ready() returns false and therefore, no data is returned from the reader.
dzarrasAuthor Commented:

Encoding makes no difference.

Write the data out as text via a PrinterWriter, and in the URLConnection:


con.setRequestProperty("Content-Type", "text/html");

And, regardless, request.getReader().ready() always returns false, even if there is data there.

Hope this saves someone some grief.
Mick BarryJava DeveloperCommented:
> Encoding makes no difference.

told you :)
dzarrasAuthor Commented:
"Abandoned" is fine, considering I basically solved the problem on my own.    I wasn't sure how to deal with such a situation (where it's solved but with no one earning any points).   I hope the answer is still helpful to someone else, however.
PAQed, with points refunded (500)

Community Support Moderator

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.