【问题标题】:Stream is closed error by closing connection关闭连接导致 Stream is closed 错误
【发布时间】:2015-03-11 05:09:55
【问题描述】:

我正在使用这个功能 -

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 错误, 但是,如果我评论 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();
}

【问题讨论】:

  • 我也尝试在 finally 块中关闭连接,但不工作,同样的事情发生。
  • stackoverflow.com/questions/9150200/… 这个链接应该有帮助。
  • @Sarah 我已经准备好最终关闭,但没有工作。请阅读我的第一条评论。
  • 您能否提供一个示例,说明您从何处调用此 GetResponse() 方法?

标签: java io stream httpurlconnection httpsurlconnection


【解决方案1】:

来自JavaDoc of HttpURLConnection(HttpsURLConnection 扩展):

如果此时持久连接处于空闲状态,则调用 disconnect() 方法可能会关闭底层套接字。

在您的 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
}

【讨论】:

  • 在这个OpenJDK source code link中,disconnect()确实关闭了InputStream。这并不一定意味着 Oracle 的 JDK 代码完全相同(我找不到 HttpsURLConnection 的 Oracle 源代码),但我希望行为非常相同以满足 @ 中描述的接口987654323@.
猜你喜欢
  • 2020-08-11
  • 1970-01-01
  • 2012-06-25
  • 2018-04-10
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
相关资源
最近更新 更多