从getInput / OutputStream()获取输入/输出流是否会影响底层Socket的重新创建?

时间:2013-03-22 12:22:55

标签: java android http networking

我已经查看了资源,这些资源描述了使用HttpURLConnection的工作细节,就像在Java中那样在Android中(没有使用连接池的默认实现),我的问题是:如果我关闭从HttpURLConnection获取的流,系统会在下次与Socket建立HttpURLConnection时创建新的URL,或者尝试使用存在一个?考虑以下代码:

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

1 个答案:

答案 0 :(得分:0)

你的问题没有意义。如果没有连接池,则没有“现有套接字”可供重用。