您的位置:首页 > 理论基础 > 计算机网络

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);
}
});

}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  okhttp工具类