user2144223
user2144223

Reputation: 11

Intermittent "Socket closed" exception with HttpUrlConnection

I have a servlet application running under jboss 7.1.1/java 1.7 that sends http requests to another server. Everything works fine for most of the time, but occasionally (from one to a couple of times a day) we get a “Socket closed” exception. I’ve been trying to find out what might be causing this but so far I’ve been unsuccessful. By the way, this has been happening while the application was running under older versions of Jboss/Java so the versions might not be that relevant.

Here’s an excerpt from the method where this happens:

. . . . .

try

{

    HttpURLConnection conn = (HttpURLConnection) urlEndpoint.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
    conn.setRequestProperty("charset", "UTF-8");
    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.write(env.getBytes("UTF-8"));
    out.flush();
    out.close();
    InputStream iss = null;
    conn.connect();
try
{
    iss = conn.getInputStream(); // this is where the exception is caught

. . . . . .

And here’s what the exception looks like:

. . . . . .

java.net.SocketException: socket closed
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:150)
    at java.net.SocketInputStream.read(SocketInputStream.java:121)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
    at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:633)
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:579)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1322)               

. . . . . .

I came across some posts that were mentioning the sockets pool the http connection is keeping, but I’m not sure whether and how this can help me solve the problem I have.

I’ve now exhausted all the ideas I had and I would be grateful for any help.

Upvotes: 0

Views: 2205

Answers (1)

user207421
user207421

Reputation: 310913

It would make more sense to call conn.connect() before doing any I/O. It doesn't make any sense at all to do it afterwards. You don't need to close the output stream.

Upvotes: 1

Related Questions