All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.aaronbedra.web.request.OkHttpRestClient Maven / Gradle / Ivy

package com.aaronbedra.web.request;

import com.jnape.palatable.lambda.io.IO;
import com.jnape.palatable.lambda.monad.transformer.builtin.ReaderT;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

import static com.aaronbedra.web.request.SimpleCookieJar.simpleCookieJar;
import static com.jnape.palatable.lambda.monad.transformer.builtin.ReaderT.readerT;

public class OkHttpRestClient extends RestClient, Request, Response, Cookie> {
    private OkHttpRestClient(OkHttpClient okHttpClient, ReaderT, Response> requestReader) {
        super(requestReader, url -> okHttpClient.cookieJar().loadForRequest(url));
    }

    public static OkHttpRestClient okHttpRestClient() {
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .followRedirects(false)
                .followSslRedirects(false)
                .cookieJar(simpleCookieJar())
                .build();

        return new OkHttpRestClient(okHttpClient, reader(okHttpClient));
    }

    private static ReaderT, Response> reader(OkHttpClient okHttpClient) {
        return readerT(request -> IO.externallyManaged(() -> {
            CompletableFuture responseFuture = new CompletableFuture<>();
            okHttpClient.newCall(request).enqueue(responseCallback(responseFuture));
            return responseFuture;
        }));
    }

    private static Callback responseCallback(CompletableFuture responseFuture) {
        return new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                responseFuture.completeExceptionally(e);
            }

            @Override
            public void onResponse(Call call, Response response) {
                responseFuture.complete(response);
            }
        };
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy