MobileUI LogoMobileUI
/

🔌 OkHttp

Fetching data from the internet


The OkHttp Plugin PURPLE adds the dependencies for the popular OkHttp Library to your project. While you could actually add these dependencies on your own, this plugin adds additional metadata for RoboVM, making OkHttp's integration much easier. Additionally, we have tested the linked version of OkHttp with the rest of the MobileUI framework libraries and confirm compatibility with all current MobileUI components.

Plugin Infos
Dependency"io.nevernull:mobileui-plugin-okhttp"
Api DocsOfficial OkHttp Documentation
Main InterfaceOkHttpClient from the official OkHttp Documentation

Example Usage

With MobileUI Inject, it's a great idea to configure one or more OkHttpClients as singletons for your application. You can do this in Micronaut factory as shown below.

Config.java
@Factory
public class Config {

    @Singleton
    public OkHttpClient okhttpClient() {
        OkHttpClient client = new OkHttpClient.Builder().build();
        return client;
    }
}

Once you have the client as Singleton, you can inject it into your controllers. The following example shows, how you can use OkHttp to call an API. To prevent network IO happening on the main thread, you should use OkHttp's asynchronous Call API. Once, you have a result, you can securely call MobileUI.firePropertyChanged(...) also from the background thread. MobileUI will make everything correct for you 🤘. You should, however, consider to make your fields volatile that are changed from the callbacks (background thread) as shown below.

OkHttpController.java
@Prototype
public class OkHttpController {

    private OkHttpClient client;
    public volatile String sslResult = "";

    public OkHttpController(OkHttpClient client) {
        this.client = client;
    }

    public void onCheckClicked() {
        Request request = new Request.Builder().url("https://www.howsmyssl.com/a/check").build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                sslResult = response.body().string();
                MobileUI.firePropertyChanged(OkHttpController.this, "sslResult");
            }
            @Override
            public void onFailure(Call call, IOException e) {
                sslResult = e.getMessage();
                MobileUI.firePropertyChanged(OkHttpController.this, "sslResult");
                e.printStackTrace();
            }
        });
    }
}

Further Reading