使用 HttpUrlConnection 和 InputStream 下载 PDF 文件

Downloading a PDF file with HttpUrlConnection and InputStream

我是 Android 开发的初学者。我正在尝试找出使用 AsyncTask 下载文件的方法。到目前为止,我已经能够下载 HttpUrlConnectionInputStream,但是我找不到任何有关从 URL 下载文件的信息。正如我所说,我在这方面很陌生。大部分代码来自我个人的知识。我从一篇文章中得到了 Http 连接和输入流的代码。我想知道下一步。

public class MainActivity extends AppCompatActivity {
    Button downloadPDF;
    DownloadingClass downPDF;
    private static final String TAG = "omar.asynctaskdemo;";
    String urlExample = "https://doc.lagout.org/programmation/Actionscript%20-%20Flash%20-%20Flex%20-%20Air/Flash%20Development%20for%20Android%20Cookbook%20-%20Labrecque%20-%20Packt%20%282011%29/Flash%20Development%20for%20Android%20Cookbook%20-%20Labrecque%20-%20Packt%20%282011%29.pdf";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadPDF = findViewById(R.id.download_pdf);
        downPDF = new DownloadingClass();

        downloadPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downPDF.execute();
            }
        });

        permissionCheck();
    }

    private void permissionCheck() {
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
                return;
            }
        }
    }

    private class DownloadingClass extends AsyncTask<String, Integer, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            URL url;
            try {
                url = new URL(urlExample);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                InputStream inputStream = httpURLConnection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line = bufferedReader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

您可以尝试创建一个 FileOutputStream,并将 InputStream 中的字节写入文件。

看看 FileOutputStream 及其 "write(byte[] b)" 方法。 https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html