engine mode encapsulates the asynchronous GET of OkHttp

Keywords: OkHttp

OkHttpEngine

First, OkHttp is obtained through the singleton mode. The singleton pattern has a private constructor and a static get method. Let's see what we've done in the constructor first.

    private OkHttpEngine(Context context) {
        File sdcache = context.getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024;
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20,TimeUnit.SECONDS)
                .readTimeout(20,TimeUnit.SECONDS)
                .cache(new Cache(sdcache.getAbsoluteFile(),cacheSize));
        mOkHttpClient = builder.build();
        mHandler = new Handler();
    }

Two main things have been done:

  • The OkHttpClient is constructed by the creator mode, and the cache address and cache size are set.
  • A new handler has been created.

Then, in the getInstance method, the double check lock is used to get a single instance.

    public static OkHttpEngine getInstance(Context context){
        if (mInstance == null){
            synchronized (OkHttpEngine.class){
                if (mInstance  == null){
                    mInstance = new OkHttpEngine(context);
                }
            }
        }
        return mInstance;
    }

Then send the asynchronous request:

    public void getAsynHttp(String url,ResultCallback callback){

        final Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = mOkHttpClient.newCall(request);
        dealResult(call, callback);
    }

Three things were done:

  1. Build request.
  2. OkHttpClient gets the call according to the request.
  3. dealResult processes the results based on the call and callback results.

dealResult

   private void dealResult(Call call, final ResultCallback callback) {
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailedCallback(call.request(), e, callback);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                sendSuccessCallback(response.body().string(), callback);
            }
        });
    }

call implements Callback asynchrony through enqueue method, and rewrites the onFailure and onResponse methods of Callback results. Finally, sendFailedCallback and sendSuccessCallback methods are called.

sendSuccesCallback

    private void sendSuccessCallback(final String str,final ResultCallback callback) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null){
                    try {
                        callback.onResponse(str);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

Start the sub thread to send the request through the handler's post method. Here, callback is an abstract class, and the method needs to be overridden.

Then send the request through Engine in the main thread.

    private void getAsynForEngine() {
        OkHttpEngine.getInstance(MainActivity.this).getAsynHttp(
            "http://www.baidu.com", new ResultCallback() {
                @Override
                public void onError(Request request, Exception e) {

                }

                @Override
                public void onResponse(String str) throws IOException {
                    Log.d(TAG, str);
                    Toast.makeText(getApplicationContext(),"Request successful",
                            Toast.LENGTH_SHORT).show();
                }
            });
    }

Get the engine object directly and call getAsynHttp method to override onError and onResponse methods.

Posted by cameeob2003 on Wed, 20 Nov 2019 07:18:15 -0800