通过一个连接从不同域下载文件 [英] Download files from different domains with one connection
问题描述
这个问题可能听起来有点疯狂,但我只是想节省时间和精力.在移动设备上打开连接需要时间和精力,因此我想尽可能重复使用打开的连接.
Well this question may sounds a little crazy but I just want to save time and engergy. To open a connection needs time and engergy on a mobile device so I want to reuse open connections if possible.
我可能需要从 example.com
和 example.net
下载文件.两个站点都托管在同一服务器/IP 上,因此应该可以通过一个连接从两个文档中获取文档.
It can happen that I'll need to download files from example.com
and example.net
. Both sites are hosted on the same server/ip so it should be possible to get documents from both documents with just one connection.
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 标头指向第一个域.我该如何解决?
The problem is when I don't use that HttpHost
for each call is a new connection established. If I use that both Host
HTTP headers points to the first domain. How can I fix that?
推荐答案
解决方案很简单(如果你找到了):
The solution is quiet simple (if you found it):
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
.
So will the connection be reused because it's the same domain/port/schema and the DefaultHttpClient
will look for that parameter ClientPNames.VIRTUAL_HOST
.
我找到了 android 实际使用的源代码的解决方案,可以在 code.google.com.
I found the solution with the sourcecode which is actuall used by android which is to find on code.google.com.
这篇关于通过一个连接从不同域下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!