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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19824339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:30:19  来源:igfitidea点击:

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

javasocketshttpurlconnection

提问by Maciej Skrzypiński

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?

有人有任何想法吗?

采纳答案by Joni

"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.

服务器中也可能存在错误:请求中的某些内容导致内部错误,服务器只是关闭连接而不是像它应该发送的那样发送 HTTP 错误响应。一些人认为这是由请求中缺少标头或无效标头值引起的。

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.

有了可用的信息,就不可能说出出了什么问题。如果您有权访问有问题的服务器,您可以使用数据包嗅探工具来查找发送和接收的确切内容,并查看服务器进程的日志以查看是否有任何错误消息。

回答by SeahawksRdaBest

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.

我建议使用wireshark来跟踪数据包。如果您使用的是 Ubuntu,请使用 sudo-apt 获取wireshark。正如 Joni 所说,找出问题所在的唯一方法是遵循 GET 请求及其相关响应。

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

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

回答by Andreas Panagiotidis

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

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

回答by Cory Klein

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 SocketExceptionwith message "Unexpected end of file from server" in a very specific circumstance.

HTTPClient此处找到的Java会SocketException在非常特殊的情况下抛出带有消息“来自服务器的文件意外结束”的消息。

After making a request, HTTPClientgets an InputStreamtied to the socket associated with the request. It then polls that InputStreamrepeatedly until it either:

发出请求后,HTTPClient得到一个InputStream绑与请求关联的插座。然后它InputStream反复轮询,直到它:

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

In case of number 2, HTTPClientwill throw this SocketExceptionifany of the following are true:

在数字 2 的情况下,如果以下任何一项为真,HTTPClient将抛出此问题:SocketException

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

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:

这表明在服务器能够发送响应之前 TCP 套接字已关闭。这可能由于多种原因而发生,但一些可能性是:

  • 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),从而导致此确切错误。

回答by zhouzhichao

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

我发现“Content-type”不应​​该是“JSON”,错了!我通过将此行更新到下面来解决此异常

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

you can check up your "Content-type"

你可以检查你的“内容类型”

回答by Filipe Manuel

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);

回答by Kris

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

您设置的标题很可能不正确或不可接受。

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

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

回答by CodeToLife

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

在我的情况下 url 包含错误的字符,如空格。总体记录您的网址,并在某些情况下使用浏览器。