private Exception exception;
private FileOutputStream fos = null;
private InputStream is = null;
private void downloadFile(String downurl, String path, String filename, String requestType,Map<String, String> requestProperty){
int mTimeout = 60 * 1000;
try {
HttpURLConnection connect = (HttpURLConnection) new URL(downurl).openConnection();
connect.setRequestMethod(requestType);
connect.setRequestProperty("Accept-Encoding", "identity");
connect.setReadTimeout(mTimeout);
connect.setConnectTimeout(mTimeout);
if (requestProperty != null) {
for (Map.Entry<String, String> entry : requestProperty.entrySet()) {
connect.setRequestProperty(entry.getKey(), entry.getValue());
}
}
connect.connect();
int responseCode = connect.getResponseCode();
Log.d("DefaultDownloadProxy", " Content-Type: %s" + connect.getContentType());
if (responseCode == HttpURLConnection.HTTP_OK) {
is = connect.getInputStream();
long length = connect.getContentLength();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
length = (int) connect.getContentLengthLong();
}
int progress = 0;
byte[] buffer = new byte[4096];
int len;
File file = new File(path, filename);
boolean isExist = file.exists();
if (isExist){
return;
}
Log.e("DefaultDownloadProxy", "file 是否存在: " + isExist);
fos = new FileOutputStream(file);
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
progress += len;
publishProgress(progress, length);
}
fos.flush();
connect.disconnect();
} else {
throw new ConnectException(String.format("responseCode = %d", responseCode));
}
} catch (Exception e) {
this.exception = e;
Log.d("DefaultDownloadProxy", e.toString());
}finally {
try {
if (null != fos){
fos.close();
}
}catch (Exception e){
e.printStackTrace();
}
try {
if (null != is){
is.close();
}
}catch (Exception e){
e.printStackTrace1();
}
}
}
private void updateProgress(int progress, long length){ ...... }