Encapsulation method of OkHttpClient

Keywords: network Java

OKHttpClient is a network request method, which is relatively simpler and more powerful than URLHttpConnection, and is favored by programmers (all of which are my own solutions)

ok, let's talk about the encapsulation method

First we define a class

OKHttpUtil.java as shown in the figure

Then enter this class

public class OkHttpUtil implements Interceptor {
    //1. Declare OkHttpUtil class object
    private static OkHttpUtil okHttpUtil;
    private static OkHttpClient okHttpClient;
    public static final long MAX_SIZE = 8 * 1024 * 1024;

    //2. Privatization of construction method
    private OkHttpUtil() {
        okHttpClient = new OkHttpClient();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //Set read timeout, write timeout and connection timeout according to builder mode settings
        builder.readTimeout(5000, TimeUnit.MILLISECONDS);
        builder.writeTimeout(5000, TimeUnit.MILLISECONDS);
        builder.connectTimeout(5000, TimeUnit.MILLISECONDS);
        //Set cache
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ACache");
        if (!file.exists())
            file.mkdir();
        Cache cache = new Cache(file, MAX_SIZE);
        builder.cache(cache);
        //Set up the log interpolator of okhttp3
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        //Set up the interpolator
        builder.addNetworkInterceptor(this);
        builder.addNetworkInterceptor(loggingInterceptor);
    }

    //3. Provide public methods for other classes to access and obtain objects of this class
    public static OkHttpClient newInstance() {
        if (null == okHttpUtil) {
            synchronized (OkHttpUtil.class) {
                if (null == okHttpUtil) {
                    okHttpUtil = new OkHttpUtil();
                }
            }
        }
        return okHttpClient;
    }

    public static void get(String urlString, Callback callback) {
        Request request = new Request.Builder().url(urlString).build();
        okHttpClient.newCall(request).enqueue(callback);
    }
    public static void post(String url, RequestBody body, Callback callback){
//        1. Create RequestBody object and set submission parameters
//        2. Create the Request object, set the Request address, and the Request method: Post: there are two ways: one is to call the post method, and the other is to call the method method
        Request request = new Request.Builder().url(url)
//                .post(body)
                .method("POST",body)
                .build();
        //3. Get the Call object through the newCall method of OkHttpClient class
        Call call = okHttpClient.newCall(request);
        //4. Call object initiates synchronous or asynchronous request
        call.enqueue(callback);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        /*
          1,Get the request object through the Chain object: chain.request();
          2,Re launch the request through the Chain object, and obtain the Response object: Chain. Processed (request);
          3,Reset the cache policy of Response to get a new Response object: remove the header information: Pragma, cache control, add:. AddHeader ("cache control", "Max age =" + 1000 * 20)
          4,Return the new Response object*/
        //Max age = 20 function: set the time to cache data
        Request request = chain.request();
        Response proceed = chain.proceed(request);
        Response pragma = proceed.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").addHeader("Cache-Control", "max-age=20").build();
        return pragma;
    }
}

All right, we're done adding

I hope this code will help some people

Posted by jlryan on Fri, 03 Jan 2020 22:54:00 -0800