Android中的Apache HttpClient下载附件极慢 [英] Apache HttpClient in Android extremely slow downloading attachment
问题描述
我正在尝试使用 HttpCLient 4 下载一个 zip 文件,它的速度约为 0.5(千字节/千位)?每分钟.该文件小于 1 MB,下载可能需要一个小时!难道我做错了什么?我还应该怎么做?这是我目前的实现:
I am trying to download a zip file using HttpCLient 4 and it is going at around .5 (kilobytes/kilobits)? per minute. The file is less than a MB large, and the download will probably take an hour! Am I doing something wrong? How else should I do this? Here is my current implementation:
@Override
protected Uri doInBackground(String... params) {
publishProgress("Downloading...");
try {
HttpPost searchPOST = new HttpPost("http://www.somesite.com/" + searchResult.getURLSuffix());
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
//added parameters here...
UrlEncodedFormEntity paramsEntity = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
searchPOST.setEntity(paramsEntity);
HttpResponse manualResponse = client.execute(searchPOST);
Header fileNameHeader = manualResponse.getFirstHeader("Content-Disposition");
Pattern p = Pattern.compile("filename=\"(.+?)\"");
Matcher m = p.matcher(fileNameHeader.getValue());
if (m.find()) {
String fileName = m.group(1);
InputStream zipStream = manualResponse.getEntity().getContent();
File cacheDir = context.getCacheDir();
String tempFileForZip = cacheDir.getAbsolutePath() + "/" + fileName;
FileOutputStream fos = new FileOutputStream(tempFileForZip);
int bytesDownloaded = 0;
try {
int c;
while ((c = zipStream.read()) != -1) {
fos.write(c);
bytesDownloaded++;
kilobytesDownloaded=(bytesDownloaded / 1000);
publishProgress((String[])null);
}
} finally {
if (zipStream != null) {
zipStream.close();
}
if (fos != null) {
fos.close();
}
}
fos.close();
String zipFilePath = tempFileForZip;
//Change to indeterminate
kilobytesDownloaded = fileSize;
publishProgress("Extracting...");
//TODO: Preferences for save directory
saveDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "Downloads/");
ZipTools.unzipArchive(new File(zipFilePath), saveDirectory);
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
return Uri.fromFile(saveDirectory);
}
推荐答案
第 1 步:不要为每个字节调用 publishProgress()
.
Step #1: Do not call publishProgress()
for every byte.
第 2 步:一次读取一个以上的字节.更好的是,不要直接使用 InputStream
-- 使用 HttpEntity#writeTo()
让 HttpClient
将您的数据写入输出文件.
Step #2: Read more than a byte at a time. Better yet, don't use the InputStream
directly -- use HttpEntity#writeTo()
to have HttpClient
write your data to the output file.
这篇关于Android中的Apache HttpClient下载附件极慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!