Simple encapsulation of OkHttpClient network request

OkHttp3 package

First, let's take a look at OkHttp

OkHttp is a sophisticated network request library with the following features:

1) Support http2, share the same socket for all requests of one machine
2) Built in connection pool to support connection reuse and reduce latency
3) Support transparent gzip compression response body
4) Avoid duplicate requests through caching
5) Automatically retry the host's other ip when the request fails, and automatically redirect
6) Easy to use API

How to use it?

Import dependency:

implementation 'com.squareup.okhttp3:okhttp:3.9.1'

Define an interface and put two methods to be used (onFailed(),onSuccess())

public interface OnFinishListener {

    void onFailed(String msg);

    void onSuccess(Object obj);
}

public class OkHttpUtils {

    private static OkHttpUtils OK_HTTP_UTILS = null;
    //Define a Handler
    private static Handler handler = new Handler();

    private OkHttpUtils() {
    }
    /**
     * Get OkHttpUtils instance object
     *
     * @return
     */
    public static OkHttpUtils getInstance() {

        if (null == OK_HTTP_UTILS) {

            synchronized (OkHttpUtils.class) {

                if (null == OK_HTTP_UTILS) {
                    OK_HTTP_UTILS = new OkHttpUtils();
                }
            }
        }
        return OK_HTTP_UTILS;

    }

Get request method

    /**
     * Get request
     * @param onFinishListener
     */
    public void doGet(String path,Map<String,String> map,final OnFinishListener onFinishListener) {

        StringBuffer sb = new StringBuffer();
        sb.append(path);
        //Determine whether the path contains a
        if(sb.indexOf("?") != -1){

            //Determine if "? Is the last
            if(sb.indexOf("?") != sb.length() -1){
                sb.append("&");
            }

        }else{
            sb.append("?");
        }

        //Traverse all request parameters in map set
        for (Map.Entry<String, String> entry: map.entrySet()){
            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }

        //Determine whether the get request path finally contains an "&"
        if(sb.lastIndexOf("&") != -1){
            sb.deleteCharAt(sb.length() - 1);
        }

        OkHttpClient okHttpClient = new OkHttpClient();

        //Build request item
        Request request = new Request.Builder()
                .get()
                .url(sb.toString())
                .build();

        Call call = okHttpClient.newCall(request);
        //execute sub thread enqueue//
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                //request was aborted  
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onFinishListener.onFailed(e.getMessage());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //Get the response from the server
                final String result = response.body().string();

                //Request succeeded
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //Execute in main thread
                        onFinishListener.onSuccess(result);
                    }
                });
            }
        });

    }

Post request mode

    /**
     * post request
     *
     * @param path
     * @param map
     * @param onFinishListener
     */
    public void doPost(String path, Map<String, String> map, final OnFinishListener onFinishListener) {


        OkHttpClient okHttpClient = new OkHttpClient();

        //Objects for building parameters
        FormBody.Builder builder = new FormBody.Builder();

        //Traverse the map set to get the user's key/value
        for (String key : map.keySet()) {
            builder.add(key, map.get(key));
        }

        /*FormBody body = new FormBody.Builder()
                .add("mobile",mobile)
                .add("password",password)
                .build();*/
        //Build request item
        final Request request = new Request.Builder()
                .post(builder.build())
                .url(path)
                .build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onFinishListener.onFailed(e.getMessage());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //This sentence must be put into the sub thread
                final String result = response.body().string();

                System.out.println("OkHttUitls Thread name : " + Thread.currentThread().getName());

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onFinishListener.onSuccess(result);
                    }
                }); 
            }
        });
    }
}

How to use it?

Tags: OkHttp Mobile network socket

Posted on Fri, 01 May 2020 03:36:30 -0700 by bstruss