"SocketException: unexpected end of file from server" from a servlet, but not from a standalone application

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 the exact same code to call (I get an error in the last line of code):

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

With the suspicion that this code cannot read the response of the remote servlet, the servlet may not be responding at all. However, why does it respond when I call it from a standalone application? 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) 

Does anyone have any ideas? Is it possible for servlets there are restrictions on the use of HttpURLConnection? Thanks!

+4
source share
3 answers

This may occur because the Content-Length header is not set. And because the body of the POST end request is not sent. The server ends waiting before the timeout for the end of the stream expires.

You should try these two things to get them working:

  • Set the content length header with the request body size before connect()
  • Try closing connection.getOutputStream().close() , which will send the end of the POST request.
+4
source

Look at the url you click. I had the same problem, and after many regressions it became known that the url created and deleted had an empty space in it, and this was the cause of the problem, we solved it by replacing space with underscore
You can also encode it to url by calling URIEncoder.encode(uri); Remember that only part of the uri should be encoded after ? .

+3
source

In our case, the tomcat protocol was set to http2 (the forced use of the http2 protocol was removed by default), but the client used http1.1, it was also necessary to sign java using a certificate, so the main problem is a bit complicated ....

0
source

All Articles