Okhttp工具类——缓存图片
2017-12-26 00:00
260 查看
package com.example.cache; import android.content.Context; import java.io.IOException; import okhttp3.Cache; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Created by 潘明杰 on 2017/12/26. */ public class OKHttpUtils { private static OKHttpUtils utils; private OkHttpClient client; private OKHttpUtils(Context context){ //缓存代码 Cache cache = new Cache(context.getCacheDir(),1024*1024*8); client = new OkHttpClient.Builder().cache(cache).addNetworkInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response proceed = chain.proceed(request); Response pragma = proceed.newBuilder() .removeHeader("Pragma") .removeHeader("Cache-Control") .addHeader("Cache-Control", "max-age=" + 1000 * 30) .build(); return pragma; } }).build(); } public static synchronized OKHttpUtils getInstance(Context context){ if(utils==null) utils = new OKHttpUtils(context); return utils; } public void sendGet(String url, Callback callback){ Request request = new Request.Builder().url(url).build(); Call call = client.newCall(request); call.enqueue(callback); } public void sendPOST(String url, RequestBody body, Callback callback){ Request request = new Request.Builder().url(url).method("POST",body).build(); Call call = client.newCall(request); call.enqueue(callback); } }
//第二步
直接用工具类调用
OKHttpUtils.getInstance(MainActivity.this).sendGet(URL, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { final String string = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { Gson gson = new Gson(); Bean bean = gson.fromJson(string, Bean.class); datas = bean.getData().getDatas(); RecyAdapter adapter = new RecyAdapter(MainActivity.this,datas); LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this); manager.setOrientation(LinearLayoutManager.VERTICAL); recyciew.setLayoutManager(manager); recyciew.setAdapter(adapter); } }); } });
相关文章推荐
- 图片相关操作的工具类 下载 ,缓存到文件
- IM模块-缓存图片视频简单工具类
- Android 图片三级缓存机制工具类封装
- 使用okhttp3做Android图片框架Picasso的下载器和缓存器
- Unity+NGUI打造网络图片异步加载与本地缓存工具类(一)
- 【Unity3D自学记录】打造网络图片异步加载与本地缓存工具类
- Unity+NGUI打造网络图片异步加载与本地缓存工具类
- OkHttp缓存工具类----饿汉式
- 工具类 得到屏幕的宽度,高度,打开浏览器,判断控件是否在屏幕中,查看图片是否已经缓存
- android 图片工具类 (图片压缩 图片长按缓存 Bitmap转Base64 Bitmap转File File转Bitmap 打开系统相册解析URI)
- 通用工具类-异步加载图片&缓存提取
- Android开源项目发现--- 工具类图片缓存篇(持续更新)
- 【android】实现图片的三级缓存。工具类
- 几个常用的工具类-异步下载、handler下载工具类、图片缓存等
- Android 图片三级缓存机制工具类封装
- Android 图片三级缓存机制工具类封装
- Android开源项目发现--- 工具类图片缓存篇(持续更新)
- 图片缓存工具类
- 图片缓存工具类
- OkHttp工具类+RecyclerView+点击事件+Glide显示图片