簡體   English   中英

從getInput / OutputStream()獲得的輸入/輸出流的關閉是否會影響底層Socket的重新創建?

[英]Does closing of input/output stream gotten from getInput/OutputStream() affects recreation of underlying Socket?

我已經瀏覽過描述Java中HttpURLConnection工作細節的資源,因此在Android中(那里沒有使用連接池的默認實現),我的問題是:如果我關閉從HttpURLConnection獲得的流,系統是否會在下一次使用相同的URL建立HttpURLConnection時創建一個新的Socket ,否則它將嘗試使用一個存在的Socket 考慮以下代碼:

private byte[] downloadText(URL url, String data) {
   OutputStream out = null;
   InputStream in = null;
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();

   try {
      conn.setRequestMethod("POST");
      conn.setReadTimeout(20 * 1000);
      conn.setConnectTimeout(15 * 000);
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

      byte[] payload = data.getBytes("utf-8");
      conn.setFixedLengthStreamingMode(payload.length);

      conn.connect();

      out = new BufferedOutputStream(conn.getOutputStream());
      out.write(payload);
      out.flush();

      final int responseCode = conn.getResponseCode();
      final String responseMessage = conn.getResponseMessage();

      is = conn.getInputStream();

      if((responseCode / 100) == 2 || responseMessage.equals("OK")) {
         return readFromStream(is);
      }
   } catch (IOException e) {
      Log.e(TAG, "Error occurred while trying to connect to the server" + e.toString());
   } finally {
      try {
         if(out != null) {
             out.close();
         }

         if(is != null) {
            is.close();
         }
      } catch(IOException e) {
         Log.e(TAG, "Error occurred while trying to close data streams" + e.toString());
      }
   }
}

您的問題沒有道理。 如果沒有連接池,則沒有“現有套接字”可重用。

暫無
暫無

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

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