廢話不多說了,直接給大家貼代碼了,具體代碼如所示:
/** * get方法的文件下載 * <p> * 特別說明 android/57594.html">android中的progressBar是google唯一的做了處理的可以在子線程中更新UI的控件 * * @param path */ private void httpDown(final String path) { new Thread() { @Override public void run() { URL url; HttpURLConnection connection; try { //統(tǒng)一資源 url = new URL(path); //打開鏈接 connection = (HttpURLConnection) url.openConnection(); //設(shè)置鏈接超時(shí) connection.setConnectTimeout(4000); //設(shè)置允許得到服務(wù)器的輸入流,默認(rèn)為true可以不用設(shè)置 connection.setDoInput(true); //設(shè)置允許向服務(wù)器寫入數(shù)據(jù),一般get方法不會(huì)設(shè)置,大多用在post方法,默認(rèn)為false connection.setDoOutput(true);//此處只是為了方法說明 //設(shè)置請求方法 connection.setRequestMethod("GET"); //設(shè)置請求的字符編碼 connection.setRequestProperty("Charset", "utf-8"); //設(shè)置connection打開鏈接資源 connection.connect(); //得到鏈接地址中的file路徑 String urlFilePath = connection.getURL().getFile(); //得到url地址總文件名 file的separatorChar參數(shù)表示文件分離符 String fileName = urlFilePath.substring(urlFilePath.lastIndexOf(File.separatorChar) + 1); //創(chuàng)建一個(gè)文件對象用于存儲下載的文件 此次的getFilesDir()方法只有在繼承至Context類的類中 // 可以直接調(diào)用其他類中必須通過Context對象才能調(diào)用,得到的是內(nèi)部存儲中此應(yīng)用包名下的文件路徑 //如果使用外部存儲的話需要添加文件讀寫權(quán)限,5.0以上的系統(tǒng)需要?jiǎng)討B(tài)獲取權(quán)限 此處不在不做過多說明。 File file = new File(getFilesDir(), fileName); //創(chuàng)建一個(gè)文件輸出流 FileOutputStream outputStream = new FileOutputStream(file); //得到鏈接的響應(yīng)碼 200為成功 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { //得到服務(wù)器響應(yīng)的輸入流 InputStream inputStream = connection.getInputStream(); //獲取請求的內(nèi)容總長度 int contentLength = connection.getContentLength(); //設(shè)置progressBar的Max mPb.setMax(contentLength); //創(chuàng)建緩沖輸入流對象,相對于inputStream效率要高一些 BufferedInputStream bfi = new BufferedInputStream(inputStream); //此處的len表示每次循環(huán)讀取的內(nèi)容長度 int len; //已經(jīng)讀取的總長度 int totle = 0; //bytes是用于存儲每次讀取出來的內(nèi)容 byte[] bytes = new byte[1024]; while ((len = bfi.read(bytes)) != -1) { //每次讀取完了都將len累加在totle里 totle += len; //每次讀取的都更新一次progressBar mPb.setProgress(totle); //通過文件輸出流寫入從服務(wù)器中讀取的數(shù)據(jù) outputStream.write(bytes, 0, len); } //關(guān)閉打開的流對象 outputStream.close(); inputStream.close(); bfi.close(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "下載完成!", Toast.LENGTH_SHORT).show(); } }); } } catch (Exception e) { e.printStackTrace(); } } }.start(); }總結(jié)
以上所述是小編給大家介紹的Android基于HttpUrlConnection類的文件下載實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對VEVB武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選