Apache HttpClient в Android крайне медленно загружает вложение - PullRequest
0 голосов
/ 01 августа 2010

Я пытаюсь загрузить zip-файл, используя HttpCLient 4, и он составляет около .5 (килобайт / килобит)? в минуту. Файл меньше, чем МБ, и загрузка, вероятно, займет час! Я делаю что-то неправильно? Как еще я должен это сделать? Вот моя текущая реализация:

@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 Ответ

7 голосов
/ 01 августа 2010

Шаг # 1: Не вызывать publishProgress() для каждого байта.

Шаг # 2: Читать больше байта за раз.Еще лучше, не используйте InputStream напрямую - используйте HttpEntity#writeTo(), чтобы HttpClient записал ваши данные в выходной файл.

...