A Minimalist HTTP Client: One‑Line Requests with OKHttpUtil

OKHttpUtil wraps Square's OkHttp library to provide a lightweight, easy‑to‑use HTTP client for Java and Kotlin, automatically handling HTTP/HTTPS detection, cookies, redirects, gzip, proxy and User‑Agent configuration, with Maven coordinates, Spring Boot starter support and concise code examples for GET, POST, file upload, download and custom API wrappers.

IoT Full-Stack Technology
IoT Full-Stack Technology
IoT Full-Stack Technology
A Minimalist HTTP Client: One‑Line Requests with OKHttpUtil

OKHttpUtil is a thin wrapper around Square's OkHttp that provides a lightweight, single‑line API for HTTP communication in Java.

Features

Automatically selects HTTP or HTTPS based on the URL.

Cookie handling is enabled by default, allowing session simulation after a login request.

Detects 304 redirects and follows them automatically.

Supports proxy configuration.

Customizable Referer and User‑Agent headers.

Automatically decompresses Gzip‑encoded responses.

Provides a Spring Boot starter for configuration via properties.

Minimal and intuitive API surface.

Maven Dependency

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

Latest version can be found at https://search.maven.org/artifact/io.github.admin4j/http

Basic Usage

GET Request

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

POST Request

# JSON body
Response post = HttpUtil.post(
    "https://oapi.dingtalk.com/robot/send?access_token=...",
    "{\"msgtype\": \"text\", \"text\": {\"content\": \"[Feedback] I am unique\"}}"
);
System.out.println("post = " + post);

# Form body
Map<String, Object> formParams = new HashMap<>(16);
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);

JSON Response Helper

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

File Upload and Download

# Upload
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);

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

Chainable Requests with 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 with chain
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

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

Configuration properties are bound to a HttpConfig class, for example:

public class HttpConfig {
    /** Log level */
    private HttpLoggingInterceptor.Level loggLevel = HttpLoggingInterceptor.Level.BODY;
    /** Read timeout (seconds) */
    private long readTimeout = 30;
    /** Connect timeout (seconds) */
    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;
    // getters & setters omitted

    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 Wrappers

OKHttpUtil can be used to build thin client wrappers for third‑party services. The following example shows a base EbayClient that configures common headers and a concrete EbayInventoryClient that implements an inventoryItem method.

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"));
    }
}

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);
    }
}

EbayInventoryClient client = new EbayInventoryClient(1L);
JSONObject json = client.inventoryItem(0, 10);

A similar EbayOrderClient can be created for order‑related endpoints.

Source Code

Repository: https://github.com/admin4j/common-http

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.

JavaMavenSpring BootOkHttpHTTP clientAPI wrapper
IoT Full-Stack Technology
Written by

IoT Full-Stack Technology

Dedicated to sharing IoT cloud services, embedded systems, and mobile client technology, with no spam ads.

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.