ketan sharma
ketan sharma

Reputation: 103

Stream is closed error by closing connection

I am using this function -

public BufferedReader GetResponse(String url, String urlParameters){
    HttpsURLConnection con=null;
    try{
        URL obj = new URL(url);
         con = (HttpsURLConnection) obj.openConnection();
        //add reuqest header
        con.setRequestMethod("POST");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        BufferedReader returnValue= new BufferedReader(new InputStreamReader(con.getInputStream()));
        con.disconnect();
        return returnValue;
    }
    catch(Exception e){
        System.out.println("--------------------There is an error in response function ");
        e.printStackTrace();
        LOGGER.error("There is an arror in AjaxCAll function of login controller."+e.getMessage());
        LOGGER.debug("There is an arror in AjaxCAll function of login controller.");
        return null;
    }
    finally{

    }
}

If I am using this -

con.disconnect();

Then I am getting java.io.IOException: stream is closed error, But if I comment the con.disconnect() line then everything is working fine. I don't know why this is happening.

Calling function

BufferedReader rd = utilities.GetResponse(url, urlParameters);
// Send post request
String line = "";
try{
    while ((line = rd.readLine()) != null) {   //getting error here if i close connection in response method
        // Parse our JSON response
        responsString += line;
        JSONParser j = new JSONParser();
        JSONObject o = (JSONObject) j.parse(line);
        if (o.containsKey("response")) {
            restMessage = (Map) o.get("response");
        } else {
            restMessage = (Map) o;
        }
    }
} finally{
    rd.close();
}

Upvotes: 2

Views: 5518

Answers (1)

dbank
dbank

Reputation: 1213

From JavaDoc of HttpURLConnection (which HttpsURLConnection extends):

Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.

Inside your GetResponse() method, you got a reference to the HttpsURLConnection's InputStream as a BufferedReader. However, when you used con.disconnect(), you closed that underlying InputStream.

In the code that calls the GetResponse() method, you when you later try to use the returned BufferedReader, you get an the java.io.IOException: stream is closed error because you have already indirectly closed that stream with con.disconnect().

You need to rearrange your code to not call con.disconnect() until you are finished with your BufferedReader.

This is one approach:

GetResponse():

public HttpsURLConnection GetResponse(String url, String urlParameters) {
    HttpsURLConnection con = null;
    DataOutputStream wr = null;
    try{
        URL obj = new URL(url);
        con = (HttpsURLConnection) obj.openConnection();
        //add request header
        con.setRequestMethod("POST");

        // Send post request
        con.setDoOutput(true);
        wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
    }
    catch(Exception e) { //better to catch more specific than Exception
        System.out.println("--------------------There is an error in response function ");
        e.printStackTrace();
        LOGGER.error("There is an arror in AjaxCAll function of login controller."+e.getMessage());
        LOGGER.debug("There is an arror in AjaxCAll function of login controller.");
        return null;
    }
    finally{
        if(wr != null) {
            wr.close();
        }
    }
    return con;
}

Calling code:

HttpsURLConnection con = utilities.GetResponse(url, urlParameters);
if(con == null) {
//stop processing or maybe throw an exception depending on what you want to do.
}
BufferedReader rd = null;

// Send post request
String line = "";
try{
    int responseCode = con.getResponseCode();  //what's this for? nothing is being done with the variable
    rd = new BufferedReader(new InputStreamReader(con.getInputStream()));

    while ((line = rd.readLine()) != null) {
        // Parse our JSON response
        responsString += line;
        JSONParser j = new JSONParser();
        JSONObject o = (JSONObject) j.parse(line);
        if (o.containsKey("response")) {
            restMessage = (Map) o.get("response");
        }
        else {
            restMessage = (Map) o;
        }
    }
} 
catch(Exception e) { //better to catch more specific than Exception
    //handle exception
}
finally {
    if(rd != null) {
        rd.close();
    }
    con.disconnect(); //we already checked if null above
}

Upvotes: 2

Related Questions