"SocketException:服务器中的文件意外结束"从servlet,但不是从独立应用程序 [英] "SocketException: Unexpected end of file from server" from servlet but not from standalone application
问题描述
我想从我的servlet中调用一个servlet.我可以从一个独立的应用程序中调用远程servlet,但不能从我的servlet中调用它(它在Glassfish上).我使用完全相同的代码进行通话(我在最后一行代码中得到了错误):
I would like to call a servlet from my servlet. I can call the remote servlet from a standalone application but I cannot call it from my servlet (it is on Glassfish). I use exactly the same code for the call (I get the error at the last code line):
URL serverAddress = new URL(endpoint);
//Set up the initial connection
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setReadTimeout(timeOut);
connection.setRequestProperty("Content-Type", "text/xml; charset=ISO-8859-1");
connection.connect();
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(requestBody);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
可疑的是,此代码无法读取远程servlet的响应,因此该servlet可能根本不响应.但是,当我从独立应用程序调用它时为什么会回复?我真的不明白 我有这个例外:
It is suspicious that this code can't read the response of the remote servlet so probably the servlet doesn't reply at all. However why does it reply when I call it from standlone app? I really don't understand... I got this exception:
java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:769)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:766)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
有人有什么主意吗? servlet是否有一些限制,使其不能使用HttpURLConnection?谢谢!
Has anyone any idea? Is it possible that there are restricitions for servlets not to use the HttpURLConnection? Thanks!
推荐答案
由于未设置Content-Length
标头,因此可能会发生这种情况.并且因为未发送POST结束请求主体.服务器结束等待,直到超时为止.
This might be happening because the Content-Length
header is not set. And because the End of POST request body is not sent. The server is ending up waiting till timeout for the end of stream.
您应该尝试以下两项操作使其正常工作:
You should try out these two things to get it working:
- 在执行
connect()
之前,将内容长度标头设置为请求正文的大小
- 尝试关闭发送POST请求结束的
connection.getOutputStream().close()
.
- Set the content length header with the request body size before doing
connect()
- Try closing the
connection.getOutputStream().close()
which send the end of POST request.
这篇关于"SocketException:服务器中的文件意外结束"从servlet,但不是从独立应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!