Android开发-网络编程文件下载
拉大锯
发表于
2019-12-10 22:52
4687
android开发
网路编程
安卓开发
文件下载
安卓课程
本文为android开发网络编程系列内容,权限的配置以及接口文档和后台程序,请移架到课程详情!
接口
代码
public void downFile(View view) {
new Thread(new Runnable() {
@Override
public void run() {
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
URL url = new URL(BASE_URL + "/download/11");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
httpURLConnection.setRequestProperty("Accept","*/*");
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
Log.d(TAG,"responseCode == > " + responseCode);
if(responseCode == HttpURLConnection.HTTP_OK) {
String headerField = httpURLConnection.getHeaderField("Content-disposition");
Log.d(TAG,"headerField == > " + headerField);
// int index = headerField.indexOf("filename=");
// String fileName = headerField.substring(index + "filename=".length());
// Log.d(TAG,"fileName -- > " + fileName);
String fileName = headerField.replace("attachment; filename=","");
Log.d(TAG,"fileName -- > " + fileName);
File picFile = RequestTestActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if(!picFile.exists()) {
picFile.mkdirs();
}
File file = new File(picFile + File.separator + fileName);
if(!file.exists()) {
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
inputStream = httpURLConnection.getInputStream();
byte[] buffer = new byte[1024];
int len;
while((len = inputStream.read(buffer,0,buffer.length)) != -1) {
fileOutputStream.write(buffer,0,len);
}
fileOutputStream.flush();
}
} catch(Exception e) {
e.printStackTrace();
} finally {
IOUtils.ioClose(inputStream);
IOUtils.ioClose(fileOutputStream);
}
}
}).start();
}
代码还是要敲的,敲了才算你自己的,看懂了还不够!视频课程已经上传,同学们也可以去看视频学习。
B站:程序员拉大锯,感谢同学们的支持与关注。