如何从给定的URl(https)下载文件(.bin扩展名)?

时间:2017-11-13 16:27:27

标签: android url

当我在浏览器中复制并粘贴以下网址时,会自动下载.bin文件。

https://ual-my.sharepoint.com/personal/u297956_global_ual_com/_layouts/15/guestaccess.aspx?docid=1ae092b7a943741309cad71c57b6f7d03&authkey=AT2ubDrTpyzfPCQmjxLYC9c

但是,如果我尝试使用Android代码下载相同的文件,它只下载到.bin文件,但包含html代码。我使用下面的代码。 我希望.bin可以在浏览器中手动运行时下载。 请帮忙。

代码段:

public static String downloadFile(String fileURL, String saveDir)
            throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
            int contentLength = httpConn.getContentLength();

            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = "create.bin";
                }
            } else {
                // extracts file name from URL
                fileName = "create.bin";
            }

            // opens input stream from the HTTP connection
            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = saveDir + File.separator + fileName;

            // opens an output stream to save into file
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);

            int len1 = 0;
            byte[] chunk = new byte[1024];
            while ( (len1 = inputStream.read(chunk)) > 0 ) {
                Log.e("Test","chunk: "+chunk);
                outputStream.write(chunk,0, len1);
                //mListener.notifyActionProgress(len1);
            }
            outputStream.close();
            inputStream.close();
        } 
        httpConn.disconnect();
    }

0 个答案:

没有答案