Why code shows “Error 354 (net::ERR_CONTENT_LENGTH

2019-05-30 06:49发布

I am building my HTTP WEB SERVER in JAVA.

If client request any file and that file is on that place in server, then server gives that file to client. I also made this code, and it works fine.

The part of code, that shows above functionality,

File targ = [CONTAINS ONE FILE]
PrintStream ps;
InputStream is = new FileInputStream(targ.getAbsolutePath());
            while ((n = is.read(buf)) > 0) {
                System.out.println(n);
                ps.write(buf, 0, n);
            }  

But now to make my code optimized, I replace this code with below code,

   InputStream is = null;
    BufferedReader reader = null;
    String output = null;

    is = new FileInputStream(targ.getAbsolutePath());
    reader = new BufferedReader(new InputStreamReader(is));

        while( (output = reader.readLine()) != null) {
           System.out.println("new line");
           //System.out.println(output);
           ps.print(output);
        }

But it sometimes shows one error Why code shows "Error 354 (net::ERR_CONTENT_LENGTH_MISMATCH): The server unexpectedly closed the connection.". I didn't understand, why it shows this error. This error is very weird, because server shows 200 code, that means, that file is there.

Help me please.

Edit no. 1

    char[] buffer = new char[1024*16];
    int k = reader.read(buffer);
    System.out.println("size : " + k);
    do { 
       System.out.println("\tsize is : " + k);
       //System.out.println(output);
       ps.println(buffer);
    }while(  (k = reader.read(buffer)) != -1 );

This prints all the file, but for bigger files, it shows unreadable characters.

It shows below output (Snapshot of client browser)

enter image description here

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-05-30 07:36

You do output = reader.readLine() to get the data, which omits the newline characters. Then you ps.print(output), so the newline characters are not sent to the client.

Say you read this

Hello\r\n
World\r\n

Then you send this:

Content-length: 14

HelloWorld

And then close the connection, confusing the browser as it still was waiting for the other 4 bytes.

I guess you'll have to use ps.println(output).

You would have seen this if you were monitoring the network traffic, which can prove quite useful when writing or debugging a server that is supposed to communicate using the network.

Anyway this will cause trouble if the newlines of the file and the system have a mismatch (\n vs \r\n). Say you have this file:

Hello\r\n
World\r\n

Its length is 14 bytes. However when your system treats a newline when printing as \n, your code with println() will print this:

Hello\n
World\n

Which is 12 bytes, not 14. You better just print what you read.

查看更多
登录 后发表回答