简体   繁体   English

Java简单代码:java.net.SocketException:来自服务器的文件意外结束

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

I wrote some simple code in Java, the method should connect to the website and return the BufferedReader.我用Java写了一些简单的代码,该方法应该连接到网站并返回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:当我在我的 PC 上使用它时,它工作正常,但是当我将 .jar 文件放在服务器上时,我收到此错误:

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?有人有什么想法吗?

"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.服务器中也可能存在错误:请求中的某些内容导致内部错误,并且服务器只是关闭连接而不是像应有的那样发送 HTTP 错误响应。 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.如果您有权访问相关服务器,则可以使用数据包嗅探工具来查找发送和接收的确切内容,并查看服务器进程的日志以查看是否有任何错误消息。

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. Java 的HTTPClient (在此处找到)在非常特定的情况下抛出带有消息“来自服务器的文件意外结束”的SocketException

After making a request, HTTPClient gets an InputStream tied to the socket associated with the request.发出请求后, HTTPClient获取一个与请求关联的套接字绑定的InputStream It then polls that InputStream repeatedly until it either:然后它反复轮询InputStream直到它:

  1. Finds the string "HTTP/1."查找字符串“HTTP/1”。
  2. The end of the InputStream is reached before 8 characters are read在读取 8 个字符之前到达InputStream的末尾
  3. Finds a string other than "HTTP/1."查找“HTTP/1”以外的字符串。

In case of number 2, HTTPClient will throw this SocketException if any of the following are true:在第 2 种情况下,如果以下任何一项为真, HTTPClient将抛出此SocketException

  • The HTTP method is CONNECT HTTP 方法是CONNECT
  • The HTTP method is POST and the client is set to streaming mode HTTP 方法为POST且客户端设置为流模式

Why would this happen为什么会发生这种情况

This indicates that the TCP socket has been closed before the server was able to send a response.这表明 TCP 套接字在服务器能够发送响应之前已关闭。 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客户端和服务器(nginx、路由器等)之间的某些东西终止了请求

Note: When Nginx reloads its config, it forcefully closes any in-flight HTTP Keep-Alive connections (even POSTs), causing this exact error.注意:当 Nginx 重新加载其配置时,它会强制关闭任何正在进行的 HTTP Keep-Alive 连接(甚至是 POST),从而导致这个确切的错误。

当我未设置身份验证标头或设置错误的凭据时,我确实收到此错误。

I would suggest using wire shark to trace packets.我建议使用钢丝鲨来追踪数据包。 If you are using Ubuntu, sudo-apt get wireshark.如果您使用的是 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.正如 Joni 所说,找出问题所在的唯一方法是跟踪 GET 请求及其相关响应。

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

In my case it was solved just passing proxy to connection.就我而言,只需将代理传递给连接即可解决。 Thanks to @Andreas Panagiotidis .感谢@Andreas Panagiotidis

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<YOUR.HOST>", 80)));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy);

Most likely the headers you are setting is incorrect or not acceptable.您设置的标题很可能不正确或不可接受。

Example:例子:

connnection.setRequestProperty("content-type", "application/json");

In my case url contained wrong chars like spaces .在我的情况下 url 包含错误的字符,如空格。 Overall log your url and in some cases use browser.总体记录您的网址,在某些情况下使用浏览器。

Tuve el mismo problema porque mi respuesta tardaba... y cerré mi servidor donde me salió el mismo error. Tuve el mismo problema porque mi respuesta tardaba... y cerré mi servidor donde me salió el mismo error。 El problema era porque en mi URL enviaba un req.parmas con " " espacios: por ejemplo: id="Dispositivo FDM" donde el problema era el espacio de la cadena controle ese "espacio" y volvio a funcionar correctamente!!! El problema era porque en mi URL enviaba un req.parmas con "" espacios: por ejemlo: id="Dispositivo FDM" donde el problema era el espacio de la cadena controle ese "espacio" y volvio a funcionar Correctamente!!! saludos萨卢多斯

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!我发现“Content-type”不应​​该是“JSON”,错了! I solved this exception by update this line to below我通过将此行更新到下面解决了这个异常

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

you can check up your "Content-type"你可以检查你的“内容类型”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 引起:java.net.SocketException:来自服务器的文件意外结束 - Caused by: java.net.SocketException: Unexpected end of file from server 异常:java.net.SocketException:来自服务器的文件意外结束 - Exception: java.net.SocketException: Unexpected end of file from server java.net.SocketException:来自服务器的文件意外结束 - java.net.SocketException: Unexpected end of file from server Solr SimplePostTool:读取响应时出现IOException:java.net.SocketException:服务器中的文件意外结束 - Solr SimplePostTool: IOException while reading response: java.net.SocketException: Unexpected end of file from server java.net.SocketException:服务器中的文件意外结束[但是此消息仅与一个特定的用户登录一起出现 - java.net.SocketException:Unexpected end of file from the server [but this message comes only with one particular user login javax.ws.rs.ProcessingException:java.net.SocketException:服务器中的文件意外结束 - javax.ws.rs.ProcessingException : java.net.SocketException: Unexpected end of file from server URLConnection无法发送完整的URL(java.net.SocketException:服务器上的文件意外结束) - URLConnection does not send full URL (java.net.SocketException: Unexpected end of file from server) HttpUrlConnection getOutputStream()抛出java.net.SocketException:服务器上的文件意外结束 - HttpUrlConnection getOutputStream() throwing java.net.SocketException: Unexpected end of file from server (SAXON DTD)java.net.SocketException:来自服务器的文件意外结束 - (saxon dtd)java.net.SocketException: Unexpected end of file fromserver java.net.SocketException:来自 SOCKS 服务器的错误回复 - java.net.SocketException: Malformed reply from SOCKS server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM