HttpUrlConnection getResponseCode throwing java.net.SocketException: Unexpected end of file from server
10,078
Sotirios Delimanolis was correct. The server wasn't sending the response header. In my HttpHandler, I just needed to add this bit of code. exchange.sendResponseHeaders(OK, 0);
And that solved the issue. Thanks so much guys!
Author by
CamHart
Updated on June 04, 2022Comments
-
CamHart almost 2 years
here's what I'm running into.
/** * Perform a post while retrieving an object in return. * @param urlPath path to requested resource * @param obj object to post * @return object retrieved from server */ private Object doPostGet(String urlPath, Object obj) { try { URL url = new URL("http://" + this.host + ":" + this.port + urlPath); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept", "text/xml"); con.setRequestProperty("Accept", "text/plain"); con.setDoInput(true); con.setDoOutput(true); con.connect(); xStream.toXML(obj, con.getOutputStream()); con.getOutputStream().close(); Object outObj = null; if (con.getResponseCode() == Handler.OK) { InputStream in = new BufferedInputStream(con.getInputStream()); assert in != null; outObj = xStream.fromXML(in); in.close(); } else if (con.getResponseCode() == Handler.FAILED_AUTH) { // } else if (con.getResponseCode() == Handler.BAD_REQUEST) { // } con.disconnect(); return outObj; } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } 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 java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468) at mock.communicator.Communicator.doPostGet(Communicator.java:131) at mock.communicator.Communicator.main(Communicator.java:102)
Line 131 of Communicator is "if (con.getResponseCode() == Handler.OK) {". I'm not really sure whats causing it, and I'm sort of new to this stuff so my understanding is limited. If you could help me understand what I'm doing wrong that would be great. If you need any server side code let me know, I'm running my own HttpServer using HttpHandlers.