Backend Development 10 min read

Simplified HTTP Requests with OKHttpUtil in Java and Spring Boot

This article introduces OKHttpUtil, a lightweight wrapper for OkHttp that simplifies HTTP GET, POST, file upload/download, and chainable requests in Java, provides Maven integration, Spring Boot configuration, and demonstrates how to encapsulate external APIs such as eBay with concise code examples.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Simplified HTTP Requests with OKHttpUtil in Java and Spring Boot

In the Java ecosystem, traditional HttpClient libraries like Apache HttpClient are heavyweight and cumbersome, while newer options such as OkHttp and Jodd-http are more user‑friendly but still have a learning curve; OKHttpUtil offers a thin, easy‑to‑use wrapper around OkHttp for both client‑side and server‑side HTTP calls.

OKHttpUtil Features

Automatically determines HTTP or HTTPS from the URL.

Cookie handling for session simulation.

Automatic 304 redirect handling.

Proxy, Referer, and User‑Agent configuration.

Gzip response decompression.

Spring Boot configuration support.

Minimal API for making requests.

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 Example

# JSON body
Response post = HttpUtil.post(
    "https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN",
    "{\"msgtype\": \"text\",\"text\": {\"content\":\"【Feedback】Example message\"}}"
);
System.out.println("post = " + post);

# Form request
Map
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 Handling

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
formParams = new HashMap<>();
formParams.put("key", "test");
formParams.put("file", file);
formParams.put("token", "YOUR_TOKEN");
Response response = HttpUtil.upload("https://upload.qiniup.com/", formParams);
System.out.println(response);

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

Chainable HttpRequest

# GET chain
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 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>

The starter allows custom OkHttp configuration via a Java class:

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

Encapsulating External APIs (eBay Example)

public class EbayClient extends ApiJsonClient {
    /** Store configuration */
    public EbayClient(Long storeId) {
        // TODO fetch store config
        Map
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
queryMap = new HashMap<>(2);
        queryMap.put("limit", limit);
        queryMap.put("offset", offset);
        return get("/sell/inventory/v1/inventory_item", queryMap);
    }
}

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

Source code is available at https://github.com/admin4j/common-http .

JavaSpring BootOkHttpHTTP ClientAPI Wrapper
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

login 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.