OKHttpUtil: A Lightweight HTTP Client Wrapper for Java and Spring Boot

This article introduces OKHttpUtil, a concise Java wrapper for the OkHttp library, outlines its key features, provides Maven dependency instructions, demonstrates GET, POST, file upload, download, and chained request usage, and shows how to integrate and configure it in Spring Boot as well as quickly build external API clients such as eBay.

Architect's Guide
Architect's Guide
Architect's Guide
OKHttpUtil: A Lightweight HTTP Client Wrapper for Java and Spring Boot

In the Java ecosystem, traditional HttpClient libraries like Apache HttpClient are heavyweight, while newer options such as OkHttp and Jodd-http are more convenient but still have a learning curve; OKHttpUtil offers a thin wrapper that makes HTTP requests extremely simple for both Android and server‑side applications.

Key features of OKHttpUtil include:

Automatic detection of HTTP or HTTPS based on the URL.

Automatic cookie handling for session simulation.

Automatic handling of 304 redirects.

Support for proxy, referer, and User‑Agent configuration.

Automatic Gzip decompression of responses.

Spring Boot starter support.

Minimalistic API for quick invocation.

Maven dependency:

<dependency>
    <groupId>io.github.admin4j</groupId>
    <artifactId>http</artifactId>
    <version>0.4.0</version>
</dependency>

GET request example:

Response response = HttpUtil.get("https://github.com/search", Pair.of("q", "okhttp"));
System.out.println("response = " + response);

POST request examples (JSON body and form data):

# JSON body
Response post = HttpUtil.post("https://oapi.dingtalk.com/robot/send?access_token=...", "{\"msgtype\": \"text\",\"text\": {\"content\":\"【反馈提醒】我就是我, 不一样的烟火\"}}");
System.out.println("post = " + post);

# Form request
Map<String, Object> formParams = new HashMap<>();
formParams.put("username", "admin");
formParams.put("password", "admin123");
Response response = HttpUtil.postForm("http://192.168.1.13:9100/auth/login", formParams);
System.out.println("response = " + response);

For JSON responses, HttpJsonUtil can directly return a JSONObject:

JSONObject object = HttpJsonUtil.get("https://github.com/search", Pair.of("q", "http"), Pair.of("username", "agonie201218"));
System.out.println("object = " + object);

File upload example:

File file = new File("C:\\Users\\andanyang\\Downloads\\Sql.txt");
Map<String, Object> formParams = new HashMap<>();
formParams.put("key", "test");
formParams.put("file", file);
formParams.put("token", "WXyUseb-...");
Response response = HttpUtil.upload("https://upload.qiniup.com/", formParams);
System.out.println(response);

File download example:

HttpUtil.down("https://gitee.com/admin4j/common-http", "path/");

Chained request using HttpRequest:

# GET with query and header
Response response = HttpRequest.get("https://search.gitee.com/?skin=rec&type=repository")
    .queryMap("q", "admin4j")
    .header(HttpHeaderKey.USER_AGENT, "admin4j")
    .execute();
System.out.println("response = " + response);

# POST form
Response response = HttpRequest.get("http://192.168.1.13:9100/auth/login")
    .queryMap("q", "admin4j")
    .header(HttpHeaderKey.USER_AGENT, "admin4j")
    .form("username", "admin")
    .form("password", "admin123")
    .execute();
System.out.println("response = " + response);

Spring Boot integration: add the starter dependency

<dependency>
    <groupId>io.github.admin4j</groupId>
    <artifactId>common-http-starter</artifactId>
    <version>0.4.0</version>
</dependency>

Custom configuration can be defined in a class such as:

public class HttpConfig {
    private HttpLoggingInterceptor.Level loggLevel = HttpLoggingInterceptor.Level.BODY;
    private long readTimeout = 30;
    private long connectTimeout = 30;
    private boolean followRedirects = false;
    private int maxIdleConnections = 5;
    private long keepAliveDuration = 5;
    private String userAgent = "OKHTTP";
    private boolean cookie = false;
    private ProxyConfig proxy;
    @Data
    public static class ProxyConfig {
        private Proxy.Type type = Proxy.Type.HTTP;
        private String host;
        private Integer port = 80;
        private String userName;
        private String password;
    }
}

Rapid external API encapsulation example (eBay):

public class EbayClient extends ApiJsonClient {
    public EbayClient(Long storeId) {
        // TODO fetch store configuration
        Map<String, String> config = new HashMap<>();
        basePath = "https://api.ebay.com";
        defaultHeaderMap.put("Authorization", "Bearer " + config.get("accessToken"));
        defaultHeaderMap.put("X-EBAY-C-MARKETPLACE-ID", config.get("marketplaceId"));
    }
}

Inventory client extending the base client:

public class EbayInventoryClient extends EbayClient {
    public EbayInventoryClient(Long storeId) { super(storeId); }
    public JSONObject inventoryItem(Integer limit, Integer offset) throws IOException {
        Map<String, Object> queryMap = new HashMap<>(2);
        queryMap.put("limit", limit);
        queryMap.put("offset", offset);
        return get("/sell/inventory/v1/inventory_item", queryMap);
    }
}

Order client example:

public class EbayOrderClient extends EbayClient {
    public EbayOrderClient(Long storeId) { super(storeId); }
    public JSONObject orders(String beginTime, String endTime, int limit, int offset) {
        final String path = "/sell/fulfillment/v1/order";
        String filter = MessageFormat.format("lastmodifieddate:[{0}..{1}]", beginTime, endTime);
        Map<String, Object> queryMap = new HashMap<>(8);
        queryMap.put("filter", filter);
        queryMap.put("limit", limit);
        queryMap.put("offset", offset);
        return get("/sell/inventory/v1/inventory_item", queryMap);
    }
}

Usage:

EbayInventoryClient ebayInventoryClient = new EbayInventoryClient(1L);
JSONObject jsonObject = ebayInventoryClient.inventoryItem(0, 10);

EbayOrderClient ebayOrderClient = new EbayOrderClient(1L);
JSONObject orders = ebayOrderClient.orders("2022-01-01", "2022-01-31", 20, 0);

The article concludes with author information and references to the original source.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentSpring BootOkHttpHTTP clientAPI wrapper
Architect's Guide
Written by

Architect's Guide

Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.