2

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();
}
Brian Beckett
  • 4,742
  • 6
  • 33
  • 52
ketan sharma
  • 103
  • 1
  • 4
  • 11

1 Answers1

2

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
}
dbank
  • 1,173
  • 1
  • 17
  • 29
  • 2
    In this [OpenJDK source code link](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/net/www/protocol/http/HttpURLConnection.java#HttpURLConnection.disconnect%28%29), `disconnect()` does indeed close the `InputStream`. That does not necessarily mean that Oracle's JDK code is exactly the same (I couldn't find Oracle source code for `HttpsURLConnection`), but I would expect the behavior is very much the same in order to satisfy the interface as described in the [JavaDoc](http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html). – dbank Mar 11 '15 at 07:17