The first article: OkHttp elegant encapsulation of HttpUtils gas sea snow mountain exploration

OkHttp elegantly encapsulates HttpUtils upload, download and decrypt

Introduction to the

HttpUtils has been renamed since V2.3.0 because it is no longer just a few utility classes, but a lightweight web development package with rich functionality. More like an enhanced version of OkHttp, hence the name OkHttps.

Chinese official website: okhttps.ejlchina.com/

Project Address: Gitee: gitee.com/ejlchina-zh…

GitHub:github.com/ejlchina/ok…

Install the tutorial

Maven

<dependency>
     <groupId>com.ejlchina</groupId>
     <artifactId>okhttps</artifactId>
     <version>1.0.4</version>
</dependency>
Copy the code

Gradle

implementation 'com. Ejlchina: okhttps: 1.0.4'
Copy the code

• Build. Gradle • Build. Gradle • Build.

android {
    // Omit other configurations..
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8}}Copy the code

Before we begin, let’s assume that HTTP is an HTTP instance of BaseUrl that was set up at build time (see above for details) :

HTTP http = HTTP.builder()
        .baseUrl("http://api.demo.com")
        .build();
Copy the code

OK, everything is ready. Let’s pick up where we left off.

Callback thread free switching (for Android)

In Android development, it is common to put some code into a specific thread for execution, such as the main thread (UI thread) for page updates after network requests, and the IO thread for saving files. OkHttps provides a good solution for this kind of problem.

By default, all callbacks are executed on the IO thread. Why is it designed this way? This is because OkHttps is just a pure Http toolkit for the Java domain and doesn’t have any Android dependencies on its own, so it doesn’t know what Android UI threads are. This design also gives it more possibilities outside of Android.

But with OkHttps on Android, can the UI thread problem be solved elegantly? Of course you can! The simple and crude way to do this is to configure a callback executor:

HTTP http = HTTP.builder()
       .callbackExecutor((Runnable run) -> {
           // The Handler can be removed from the actual code, so it does not need to be recreated every time a callback is executed
           new Handler(Looper.getMainLooper()).post(run); // execute on main thread
       })
       .build();
Copy the code

All callbacks are executed on the main thread (UI thread), as in:

http.async("/users")
        .addBodyParam("name"."Jack")
        .setOnProcess((Process process) -> {
            // execute on main thread
        })
        .setOnResponse((HttpResult result) -> {
            // execute on main thread
        })
        .setOnException((Exception e) -> {
            // execute on main thread
        })
        .setOnComplete((State state) -> {
            // execute on main thread
        })
        .post();
Copy the code

But what if you also want some callbacks to be placed on the IO thread for free switching? OkHttps gives a very flexible approach, as follows:

http.async("/users")
        .addBodyParam("name"."Jack")
        .setOnProcess((Process process) -> {
            // execute on main thread
        })
        .nextOnIO()          // Specify that the next callback is executed on the IO thread
        .setOnResponse((HttpResult result) -> {
            // Execute in the IO thread
        })
        .setOnException((Exception e) -> {
            // Execute in main thread (execute in callback executor if nextOnIO is not specified)
        })
        .nextOnIO()          // Specify that the next callback is executed on the IO thread
        .setOnComplete((State state) -> {
            // Execute in the IO thread
        })
        .post();
Copy the code

Either callback can be switched freely using the nextOnIO() method. The same is true for file downloads:

http.sync("/download/test.zip")
        .get()
        .getBody()
        .setOnProcess((Process process) -> {
            // execute on main thread
        })
        .toFolder("D:/download/")
        .nextOnIO()          // Specify that the next callback is executed on the IO thread
        .setOnSuccess((File file) -> {
            // Execute in the IO thread
        })
        .setOnFailure((Failure failure) -> {
            // execute on main thread
        })
        .start();
Copy the code

How about that? Is that easy?

If so, go ahead and click on a little star:

Gitee:gitee.com/ejlchina-zh…

GitHub:github.com/ejlchina/ok…


Previous article: OkHttp elegantly encapsulates HttpUtils upload, download and decrypt

Next article: OkHttp elegantly encapsulates OkHttps’s current lifecycle bindings