通过关闭连接流被关闭错误

Stream is closed error by closing connection

我正在使用这个功能 -

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{

    }
}

如果我正在使用这个 -

con.disconnect();

然后我收到 java.io.IOException: stream is closed error, 但是,如果我评论 con.disconnect() 行,那么一切正常。我不知道为什么会这样。

调用函数

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

来自 JavaDoc of HttpURLConnection(HttpsURLConnection 扩展):

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

在您的 GetResponse() 方法中,您获得了对 HttpsURLConnectionInputStream 作为 BufferedReader 的引用。但是,当您使用 con.disconnect() 时,您关闭了底层 InputStream.

在调用 GetResponse() 方法的代码中,当您稍后尝试使用返回的 BufferedReader 时,您会得到一个 java.io.IOException: stream is closed error,因为您已经间接关闭了该流con.disconnect().

您需要重新安排您的代码,以便在您完成 BufferedReader 之前不调用 con.disconnect()

这是一种方法:

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;
}

调用代码:

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
}