【问题标题】:Download files from different domains with one connection通过一个连接从不同域下载文件
【发布时间】:2012-11-08 11:14:20
【问题描述】:

这个问题听起来有点疯狂,但我只是想节省时间和精力。在移动设备上打开连接需要时间和精力,所以我想尽可能重用打开的连接。

我可能需要从example.comexample.net 下载文件。两个站点都托管在同一个服务器/IP 上,因此应该可以通过一个连接从两个文档中获取文档。

DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://example.com/robots.txt");
HttpGet get2 = new HttpGet("http://example.net/robots.txt");
URI uri = get.getURI();
HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpResponse response = client.execute(host, get);
String data = responseHandler.handleResponse(response);
Log.v("test", "Downloaded " + data.length() + " bytes from " + get.getURI().toASCIIString());
response = client.execute(host, get2);
data = responseHandler.handleResponse(response);
Log.v("test", "Downloaded " + data.length() + " bytes from " + get2.getURI().toASCIIString());

问题是当我不使用HttpHost 时,每次调用都会建立一个新连接。如果我使用这两个 Host HTTP 标头都指向第一个域。我该如何解决?

【问题讨论】:

    标签: android network-programming http-headers apache-httpclient-4.x


    【解决方案1】:

    解决方案很简单(如果你找到了):

    HttpGet get2 = new HttpGet("http://example.com/robots.txt");
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost("example.net", -1, "http"));
    get2.setParams(params);
    

    所以连接会被重用,因为它是相同的域/端口/模式,DefaultHttpClient 将寻找那个参数ClientPNames.VIRTUAL_HOST

    我在code.google.com上找到了android实际使用的源代码的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      相关资源
      最近更新 更多