简单的网络请求
1 | OkHttpClient client = new OkHttpClient(); |
图片
首先得到网络的输入流,然后使用BitmapFactory将输入流转换成图片。
1
2InputStream in = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);保存到本地。这里首先创建文件夹,然后新创建一个jpg文件,用缓冲流包装文件的输出流,最后利用图片压缩将图片写入到jpg文件中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22public void saveBitmap(String path,Bitmap bitmap, String fileName) {
File dirFile = new File(path);
BufferedOutputStream bos = null;
if (!dirFile.exists()) {
dirFile.mkdirs();
}
try {
File dayFile = new File(path, fileName + ".jpg");
bos = new BufferedOutputStream(new FileOutputStream(dayFile));
//图片压缩,100代表不压缩
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}从本地读取照片。从本地读取照片是很简单的,只需要利用BitmapFactory的解析文件的方法,解析目标图片路径即可。
1
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
音频,文件下载
首先得到输入流,然后读取输入流的字节,写入到对象文件的输出流即可
1 | InputStream in = null; |
断点下载文件
1 | OkHttpClient client = new OkHttpClient(); |
下面代码是实现断点下载文件的一个很重要的任务类。实现的任务有下载,暂停下载,取消下载等功能。大概流程为:查看本地保存的目的路径是否存在对应的文件,有则记录文件的大小。然后使用getContentLength()方法来得到需要下载文件的大小。假如记录大小和实际大小相等,则证明不需要下载,如不相等则进行断点下载。RandomAccessFile的使用是因为它可以指定位置读,指定位置写的一个类,故可以实现断点下载。通常开发过程中,多用于多线程下载一个大文件.
1 | public class DownloadTask extends AsyncTask<String, Integer, Integer> { |