从URL下载文件?

时间:2018-11-15 12:22:31

标签: java android

我正在使用以下代码下载PDF文件。

private class downloadPaper extends AsyncTask<String, String, String> {
    private ProgressDialog progressDialog;
    private boolean isDownloaded;
    private String destination = *path to folder on phone*;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        this.progressDialog = new ProgressDialog(ActivityPaper.this);
        this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        this.progressDialog.setCancelable(false);
        this.progressDialog.show();
    }
    @Override
    protected String doInBackground(String... url) {
        int count;
        try {
            URL getUrl = new URL(url[0]);
            URLConnection connection = getUrl.openConnection();
            connection.connect();
            // getting file length
            int lengthOfFile = connection.getContentLength();
            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(getUrl.openStream(), 8192);
            // Output stream to write file
            OutputStream output = new FileOutputStream(destination);
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress("" + (int) ((total * 100) / lengthOfFile));
                Log.d(TAG, "Progress: " + (int) ((total * 100) / lengthOfFile));
                // writing data to file
                output.write(data, 0, count);
            }
            // flushing output
            output.flush();
            // closing streams
            output.close();
            input.close();
            return "success";
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return getString(R.string.somethingWrong);
    }
    /**
     * Updating progress bar
     */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        progressDialog.setProgress(Integer.parseInt(progress[0]));
    }
    @Override
    protected void onPostExecute(String message) {
        // dismiss the dialog after the file was downloaded
        this.progressDialog.dismiss();
        // Display File path after downloading
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }
}

我收到以下答复,

E/Error:: Unexpected status line: <html>

我尝试将文件源URL更改为其他网站上的其他PDF,并且工作正常。仅当我尝试从服务器下载时才显示该错误。我猜这是服务器配置问题。

0 个答案:

没有答案