使用HttpURLConnection的HTTP请求不会重用TCP连接

问题描述 投票:4回答:2

我已经创建了一个将GET请求发送到URL的应用程序,然后下载该页面的完整内容。

客户端向例如stackoverflow.com发送GET,并将响应转发给解析器,解析器具有从页面中查找需要随后的GET请求下载的所有源的可靠性。

以下方法用于发送这些GET请求。 连续多次调用,解析器返回的URL。 这些URL中的大多数都位于同一主机上,并且应该能够共享TCP连接。

public static void sendGetRequestToSubObject(String RecUrl)
    {
        URL url = new URL(recUrl.toString());
        URLConnection connection = url.openConnection ();
        InputStreamReader isr = new InputStreamReader(connection.getInputStream());
    }

每次调用此方法时,都会创建一个新的TCP连接(使用TCP 3次握手),然后在该连接上发送GET。 但我想重用TCP连接,以提高性能。

我想,因为每次调用方法时我都会创建一个新的URL对象,这就是它的工作方式......

也许有人可以帮助我以更好的方式做到这一点?

谢谢!

java connection httpurlconnection persistent
2个回答
6
投票

如果可以, HttpURLConnection 重用连接!

为此,需要满足几个前提条件,主要是在服务器端。 这些先决条件在与上述相关的文章中有所描述。


2
投票

发现问题了! 我没有正确读取输入流。 这导致输入流对象挂起,并且无法重用它们。

我只定义了它,像这样:

InputStreamReader isr = new InputStreamReader(connection.getInputStream());

但我从来没有读过它:-)

我也改变了read方法。 我偷了这个,而不是一个缓冲的读卡器:

InputStream in = null; 
String queryResult = "";
try {
     URL url = new URL(archiveQuery);
     HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
     HttpURLConnection httpConn = (HttpURLConnection) urlConn;
     httpConn.setAllowUserInteraction(false);
     httpConn.connect();
     in = httpConn.getInputStream();
     BufferedInputStream bis = new BufferedInputStream(in);
     ByteArrayBuffer baf = new ByteArrayBuffer(50);
     int read = 0;
     int bufSize = 512;
     byte[] buffer = new byte[bufSize];
     while(true){
         read = bis.read(buffer);
         if(read==-1){
           break;
         }
         baf.append(buffer, 0, read);
     }
     queryResult = new String(baf.toByteArray());
     } catch (MalformedURLException e) {
          // DEBUG
          Log.e("DEBUG: ", e.toString());
     } catch (IOException e) {
          // DEBUG
          Log.e("DEBUG: ", e.toString());
     } 
}

从这里: 阅读HttpURLConnection InputStream - 手动缓冲区或BufferedInputStream?

© www.soinside.com 2019 - 2024. All rights reserved.