从Android服务器下载文件

时间:2014-12-01 17:20:51

标签: java android webview android-asynctask server

如何使用以下网址下载文件:

  

http://www.plataformarcc.net/ReportViewsMobile/Reserved.ReportViewerWebControl.axd?ReportSession=z1gjkz55kcotrb45oisj5iyp&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=2369b8ca79aa460e9604226894f8a130&OpType=Export&FileName=I_Menu_Indicadores&ContentDisposition=OnlyHtmlInline&Format=WORDOPENXML

我可以像这样用Url下载文件:

http://www.gradsch.ohio-state.edu/Depo/ETD_Tutorial/lesson2.pdf

使用此异步任务:

 private class DownloadFilePDF extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);

    }

    @Override
    protected void onPostExecute (String result){

        super.onPostExecute(result);


    }


    @Override
    protected String doInBackground(String... sUrl) {

        try {

            Log.i("File download", "Started from :"+sUrl[0]);

            URL url = new URL(sUrl[0]);
            //URLConnection connection = url.openConnection();
            File myDir = new File(Environment.getExternalStorageDirectory() + "/myDir");
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(sUrl[0]);
            request.setHeader("User-Agent", sUrl[0]);

            HttpResponse response = client.execute(request);
            // create the directory if it doesnt exist
            if (!myDir.exists()) myDir.mkdirs();



            File outputFile     =   new File(myDir, "hotmail_contacts.pdf");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            int fileLength      = connection.getContentLength();
            // download the file
            InputStream input   = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(outputFile);

            byte data[] = new byte[1024];
            long total = 0;
            int count;

            while ((count = input.read(data)) != -1) {

                total += count;
                // publishing the progress....
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }



            output.flush();
            output.close();
            input.close();

            Log.i("File download", "complete");

        } catch (Exception e) {

            Log.e("File download", "error: " + e.getMessage());

        }
        return null;
    }
}

但它不适用于第一个url,android显示此错误

11-27 13:50:26.360   9513-11482/com.example.ecollsandroidwebview E/File download﹕ error:

0 个答案:

没有答案