OkHttp封装、缓存

OkHttp的封装

public class MyOkHttp {
    private static MyOkHttp myOkHttp = new MyOkHttp();
    private OkHttpClient okHttpClient;
    private Cache cache;
    private long maxSize = 8 * 1024 * 1024;
private MyOkHttp() {

    //Environment用来管理手机SDcard内存的

    File file = new File(Environment.getExternalStorageDirectory() + "/H1706A");
    cache = new Cache(file, maxSize);

    //OKHTTPClient两种写法 第二种就是通过构造者模式也可以使用

    okHttpClient = new OkHttpClient.Builder().cache(cache).build();

}
    public static MyOkHttp getMyOkHttp() {
        return myOkHttp;
    }
同步下get,Post

public String sendGet(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    Response response = okHttpClient.newCall(request).execute();
    return response.body().string();
}
    //同步下Post

    public String sendPost(String url, RequestBody body) throws IOException {
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = okHttpClient.newCall(request).execute();
        return response.body().string();
    }
//异步的封装 GET和POST自己 预习一下缓存OkHttp如何使用缓存

public void sendAsyncGet(String url, Callback callback) {
    Request request = new Request.Builder().url(url).build();
    okHttpClient.newCall(request).enqueue(callback);
}
    //异步的POST

    public void sendAsyncPost(String url, RequestBody body, Callback callback) {
        Request request = new Request.Builder().url(url).post(body).build();
        okHttpClient.newCall(request).enqueue(callback);
    }

//测试缓存

public String sendCacheGet(String url) throws IOException {
    //要缓存数据  需要加上一个方法cacheControl
    Request request = new Request.Builder().url(url).cacheControl(new CacheControl.Builder().maxStale(24 * 60 * 60, TimeUnit.SECONDS).build()).build();
    Response response = okHttpClient.newCall(request).execute();
    return response.body().string();
}

}
···

你可能感兴趣的:(OkHttp封装、缓存)