一:OkGo介绍
该库是封装了okhttp的网络框架,可以与RxJava完美结合,比Retrofit更简单易用。支持大文件上传下载,上传进度回调,下载进度回调,表单上传(多文件和多参数一起上传),链式调用,可以自定义返回对象,支持Https和自签名证书,支持cookie自动管理,支持四种缓存模式缓存网络数据,支持301、302重定向,扩展了统一的上传管理和下载管理功能
作用:网络请求的框架(okhttp)
功能:上传,下载(图片,文件MP3,字符串)
添加依赖
implementation 'com.lzy.net:okgo:3.0.4'
二:get请求
下载json
public void downjson(View view) {
new Thread(new Runnable() {
@Override
public void run() {
OkGo.<String>get("https://news-at.zhihu.com/api/4/news/latest").execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
final String body = response.body();
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, body, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void downloadProgress(Progress progress) {
super.downloadProgress(progress);
//progress.fraction 获得当前上传进度 范围0-1
progressId.setProgress((int) (progress.fraction*100));
}
@Override
public void onError(Response<String> response) {
super.onError(response);
}
});
}
}).start();
}
下载图片
public void downphoto(View view) {
new Thread(new Runnable() {
@Override
public void run() {
OkGo.<Bitmap>get("http://i.kinja-img.com/gawker-media/image/upload/s--B7tUiM5l--/gf2r69yorbdesguga10i.gif").execute(new BitmapCallback() {
@Override
public void onSuccess(Response<Bitmap> response) {
Bitmap bitmap = response.body();
Log.i(TAG, "onSuccess: 图片大小"+bitmap.getByteCount());
imageId.setImageBitmap(bitmap);
}
@Override
public void downloadProgress(Progress progress) {
super.downloadProgress(progress);
progressId.setProgress((int) (progress.fraction*100));
}
});
}
}).start();
}
下载MP4
public void downmp3(View view) {
new Thread(new Runnable() {
@Override
public void run() {
OkGo.<File>get("http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4").execute(new FileCallback("/mnt/sdcard","jiat.mp4") {
@Override
public void onSuccess(Response<File> response) {
}
@Override
public void downloadProgress(Progress progress) {
super.downloadProgress(progress);
//如何拿到当前的下载进度
progressId.setProgress((int)(progress.fraction*100));
}
});
}
}).start();
}
post请求
public void upLoade(){
OkGo.<String>post("http://10.1.2.121/text/").isMultipart(true).params("file",new File("mnt/sdcard/aaa.mp3"),"huolai.mp3").execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
Log.d(TAG, "onSuccess: "+response.body());
}
@Override
public void uploadProgress(Progress progress) {
super.uploadProgress(progress);
}
});
}