[英]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.如果您有权访问相关服务器,则可以使用数据包嗅探工具来查找发送和接收的确切内容,并查看服务器进程的日志以查看是否有任何错误消息。
This exception is encountered when you are expecting a response, but the socket has been abruptly closed.当您期待响应时会遇到此异常,但套接字已突然关闭。
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
直到它:
InputStream
is reached before 8 characters are read在读取 8 个字符之前到达InputStream
的末尾 In case of number 2, HTTPClient
will throw this SocketException
if any of the following are true:在第 2 种情况下,如果以下任何一项为真, HTTPClient
将抛出此SocketException
:
CONNECT
HTTP 方法是CONNECT
POST
and the client is set to streaming mode HTTP 方法为POST
且客户端设置为流模式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:这可能由于多种原因而发生,但一些可能性是:
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.