/**
* get方法的文件下載
* <p>
* 特別說明 android中的progressBar是google唯一的做了處理的可以在子線程中更新UI的控件
*
* @param path
*/
private
void
httpDown(
final
String path) {
new
Thread() {
@Override
public
void
run() {
URL url;
HttpURLConnection connection;
try
{
//統一資源
url =
new
URL(path);
//打開鏈接
connection = (HttpURLConnection) url.openConnection();
//設置鏈接超時
connection.setConnectTimeout(
4000
);
//設置允許得到服務器的輸入流,默認爲true可以不用設置
connection.setDoInput(
true
);
//設置允許向服務器寫入數據,一般get方法不會設置,大多用在post方法,默認爲false
connection.setDoOutput(
true
);
//此處只是爲了方法說明
//設置請求方法
connection.setRequestMethod(
"GET"
);
//設置請求的字符編碼
connection.setRequestProperty(
"Charset"
,
"utf-8"
);
//設置connection打開鏈接資源
connection.connect();
//得到鏈接地址中的file路徑
String urlFilePath = connection.getURL().getFile();
//得到url地址總文件名 file的separatorChar參數表示文件分離符
String fileName = urlFilePath.substring(urlFilePath.lastIndexOf(File.separatorChar) +
1
);
//創建一個文件對象用於存儲下載的文件 此次的getFilesDir()方法只有在繼承至Context類的類中
// 可以直接調用其他類中必須通過Context對象才能調用,得到的是內部存儲中此應用包名下的文件路徑
//如果使用外部存儲的話需要添加文件讀寫權限,5.0以上的系統需要動態獲取權限 此處不在不做過多說明。
File file =
new
File(getFilesDir(), fileName);
//創建一個文件輸出流
FileOutputStream outputStream =
new
FileOutputStream(file);
//得到鏈接的響應碼 200爲成功
int
responseCode = connection.getResponseCode();
if
(responseCode == HttpURLConnection.HTTP_OK) {
//得到服務器響應的輸入流
InputStream inputStream = connection.getInputStream();
//獲取請求的內容總長度
int
contentLength = connection.getContentLength();
//設置progressBar的Max
mPb.setMax(contentLength);
//創建緩衝輸入流對象,相對於inputStream效率要高一些
BufferedInputStream bfi =
new
BufferedInputStream(inputStream);
//此處的len表示每次循環讀取的內容長度
int
len;
//已經讀取的總長度
int
totle =
0
;
//bytes是用於存儲每次讀取出來的內容
byte
[] bytes =
new
byte
[
1024
];
while
((len = bfi.read(bytes)) != -
1
) {
//每次讀取完了都將len累加在totle裏
totle += len;
//每次讀取的都更新一次progressBar
mPb.setProgress(totle);
//通過文件輸出流寫入從服務器中讀取的數據
outputStream.write(bytes,
0
, len);
}
//關閉打開的流對象
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();
}