第十五、十六、十七---网络下载框架
依赖
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
implementation 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
一、OkHttp
1、同步
可以直接运行,底层封装了线程
1、GET
步骤:
1、OkHttpClient:客户端 -----OkHttpClient client = new OkHttpClient();
2、Request 请求对象 -----Request r = new Request.Bulider().url(网址).get()/post(body对象).build();
3、Response 结果对象 — Response result = client.newCall®.excute();
4、获得结果 – String str = result.body().string();
2、POST
1、FormBody 放参数(表单参数) ----- FormBody body = new FormBody.Builder().add(“键”,“值”).build();
2、把body给请求对象Request对象
2、异步
必须放在子线程中运行,不需要重写接口方法
1、获得Call – Call call = client.newCall(request.请求对象);
2、重写接口方法 — call.enqueqe(new CallBack()){onFail(成功){ }; onRespone(成功){结果}};
get:
post:
二、Volley:适用于多频率高的小数据的下载
用法
1、GET
1、StringRequest str = new StringRequest(Method.GET/Methos.POST,网址,结果监听,错误监听);
2、添加队列 – RequestQueue queue = Volley.newRequestQueue(上下文);
3、添加队列 – queue.add(请求对象);
4、启动队列 – queue.start();
2、POST
1、重写getParms(){HashMap} put参数he对应的值
3、下载图片
ImageRequest image = new Imagequest(网址,结果监听,宽,高,Bitmap.Config.GRB8888,错误监听)
三、运行效果及整体代码