Java simple code: java.net.SocketException: Unexpected end of file from server

后端 未结 8 1750
盖世英雄少女心
盖世英雄少女心 2020-12-01 10:23

I wrote some simple code in Java, the method should connect to the website and return the BufferedReader.

private BufferedReader getConnection(String url_a)          


        
8条回答
  •  遥遥无期
    2020-12-01 11:03

    Summary

    This exception is encountered when you are expecting a response, but the socket has been abruptly closed.

    Detailed Explanation

    Java's HTTPClient, found here, throws a SocketException with message "Unexpected end of file from server" in a very specific circumstance.

    After making a request, HTTPClient gets an InputStream tied to the socket associated with the request. It then polls that InputStream repeatedly until it either:

    1. Finds the string "HTTP/1."
    2. The end of the InputStream is reached before 8 characters are read
    3. Finds a string other than "HTTP/1."

    In case of number 2, HTTPClient will throw this SocketException if any of the following are true:

    • The HTTP method is CONNECT
    • The HTTP method is POST and the client is set to streaming mode

    Why would this happen

    This indicates that the TCP socket has been closed before the server was able to send a response. This could happen for any number of reasons, but some possibilities are:

    • Network connection was lost
    • The server decided to close the connection
    • Something in between the client and the server (nginx, router, etc) terminated the request

    Note: When Nginx reloads its config, it forcefully closes any in-flight HTTP Keep-Alive connections (even POSTs), causing this exact error.

提交回复
热议问题