问题
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()));
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)
Has anyone any idea? Is it possible that there are restricitions for servlets not to use the HttpURLConnection? Thanks!
回答1:
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:
- 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.
回答2:
look at the url that you are hitting.
i had the same issue and after much regression came to know that url being generated and than being hit had a blank space in it and it was the cause of problem, solved it by replacing space
with underscore
You can also encode it to url by calling URIEncoder.encode(uri);
remember that only the part of uri after ?
is should be encoded.
回答3:
In our case it was tomcat set to http2 protocol (removed forcing to http2 protocol by default,
remove
<UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
from server.xml
in tomcat config
folder
, but client used http1.1, also java needed to be signed with certificate (keyimport tool), so underlying issue is a bit tricky....
来源:https://stackoverflow.com/questions/11265464/socketexception-unexpected-end-of-file-from-server-from-servlet-but-not-from