56

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

private BufferedReader getConnection(String url_a) {
        URL url;
        try {
            System.out.println("getting connection");
            url = new URL(url_a);
            HttpURLConnection urlConnection = (HttpURLConnection) 
                     url.openConnection();
            urlConnection.addRequestProperty("User-Agent",
                    "Mozilla/5.0 (X11; U; Linux i586; en-US; rv:1.7.3) Gecko/20040924"
                     + "Epiphany/1.4.4 (Ubuntu)");
            inStream = new InputStreamReader(urlConnection.getInputStream());
            return new BufferedReader(inStream);
        } catch (Exception ex) {
            Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;

}

When I use it on my PC, it works fine but when I put .jar file on the server I get this error:

java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:718)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:579)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:715)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:579)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1322)
at dataconverter.Reader.getConnection(Reader.java.260)

Problem is quite strange because the exception isn't thrown each time, sometimes everything is OK and program works fine.

Has anybody got any ideas?

edwoollard
  • 12,245
  • 6
  • 43
  • 74
Maciej Skrzypiński
  • 557
  • 1
  • 4
  • 10

8 Answers8

84

"Unexpected end of file" implies that the remote server accepted and closed the connection without sending a response. It's possible that the remote system is too busy to handle the request, or that there's a network bug that randomly drops connections.

It's also possible there is a bug in the server: something in the request causes an internal error, and the server simply closes the connection instead of sending a HTTP error response like it should. Several people suggest this is caused by missing headers or invalid header values in the request.

With the information available it's impossible to say what's going wrong. If you have access to the servers in question you can use packet sniffing tools to find what exactly is sent and received, and look at logs to of the server process to see if there are any error messages.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • I am using Socks server to make the similar call. will the problem be in the socks server or the remote server? – Dejell Jan 03 '15 at 16:31
  • 1
    It could be either. The SOCKS proxy seems like a more likely source of error though so I'd start there. – Joni Jan 03 '15 at 16:47
  • When a lot op people say it is most likely due to incorrect headers, how than can it be that the errors only appears sometimes? Why does the incorrect headers also gets accepted a lot? – Yannick Mussche Nov 21 '22 at 09:47
64

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.

Cory Klein
  • 51,188
  • 43
  • 183
  • 243
5

I do get this error when I do not set the Authentication header or I set wrong credentials.

Andreas Panagiotidis
  • 2,763
  • 35
  • 32
2

In my case it was solved just passing proxy to connection. Thanks to @Andreas Panagiotidis.

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<YOUR.HOST>", 80)));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy);
Filipe Manuel
  • 967
  • 2
  • 14
  • 33
  • My case was also proxy related. Our proxy setup uses a proxy server for all connection outside the company but requires no proxy for internal addresses. After adding the noproxy option to my JAVA_OPTS the connection worked. `JAVA_OPTS=-Dhttps.proxyHost=acme-proxy.global.acme.net -Dhttps.proxyPort=2011 -Dhttp.nonProxyHosts="*.acme.net"` – Ioannis K. Moutsatsos Aug 09 '23 at 18:01
1

I would suggest using wire shark to trace packets. If you are using Ubuntu, sudo-apt get wireshark. Like Joni stated the only way to figure out whats going wrong is to follow the GET requests and their associated responses.

http://www.wireshark.org/download.html

SeahawksRdaBest
  • 868
  • 5
  • 17
0

In my case url contained wrong chars like spaces . Overall log your url and in some cases use browser.

CodeToLife
  • 3,672
  • 2
  • 41
  • 29
-1

Most likely the headers you are setting is incorrect or not acceptable.

Example:

connnection.setRequestProperty("content-type", "application/json");
Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
Kris
  • 719
  • 1
  • 11
  • 19
  • When you say it is most likely due to incorrect headers, how than can it be that the errors only appears sometimes? Why does the incorrect headers also gets accepted a lot? – Yannick Mussche Nov 21 '22 at 09:47
-2

I got this exception too. MY error code is below

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(requestMethod);
        connection.setRequestProperty("Content-type", "JSON");

I found "Content-type" should not be "JSON",is wrong! I solved this exception by update this line to below

        connection.setRequestProperty("Content-type", "application/json");

you can check up your "Content-type"