簡體   English   中英

BufferedReader連接未關閉

[英]BufferedReader connection doesn't close

我創建了一個小型的抓取類,下面的方法從頁面中讀取文本。

但是,我發現該方法無法正確關閉連接。 這導致大量的打開連接,導致我的托管公司暫停我的帳戶。 以下是正確的嗎?

private String getPageText(String urlString) {

    String pageText = "";


        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuilder builder = new StringBuilder();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                builder.append(chars, 0, read); 

            pageText = builder.toString();
        } catch (MalformedURLException e) {
            Log.e(CLASS_NAME, "getPageText.MalformedUrlException", e);
        } catch (IOException e) {
            Log.e(CLASS_NAME, "getPageText.IOException", e);
        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException e) {
                    Log.e(CLASS_NAME, "getPageText.IOException", e);
                }
        }
        return pageText;


}

您的代碼在成功案例中沒有問題但在故障情況下可能會泄漏連接(當http服務器返回4xx或5xx狀態代碼時)。 在這些情況下,HttpURLConnection通過.getErrorStream()而不是.getInputStream()提供響應體,你應該確保排出和關閉該流。

URLConnection conn = null;
BufferedReader reader = null;
try {
  conn = url.openConnection();
  reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  // ...
} finally {
  if(reader != null) {
    // ...
  }
  if(conn instanceof HttpURLConnection) {
    InputStream err = ((HttpURLConnection)conn).getErrorStream();
    if(err != null) {
      byte[] buf = new byte[2048];
      while(err.read(buf) >= 0) {}
      err.close();
    }
  }
}

最后可能需要另外一層try / catch,但你明白了。 應該明確.disconnect()的連接,除非你肯定不會有在不久的將來,該主機上的網址,任何更多的請求- disconnect()將防止后續請求被流水線上的現有連接,這對於特別是https會大大降低速度。

您只是關閉stream而不是connection ,請使用以下結構:

URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection)
        u.openConnection();
conn.connect();

reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

接着:

} finally {
    if (reader != null)
       try {
           reader.close();
       } catch (IOException e) {
           Log.e(CLASS_NAME, "getPageText.IOException", e);
       }
    }

    try {
        if (conn != null) {
            conn.disconnect();
        }
    } catch (Exception ex) {}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM