One‑Line HTTP Requests with OKHttpUtil: A Minimal Java Wrapper
The article introduces OKHttpUtil, a lightweight wrapper around Square’s OkHttp library that enables Java developers to perform HTTP GET, POST, file upload, and download operations with a single line of code, includes Maven setup, Spring Boot integration, fluent API usage, and examples of wrapping external services such as eBay.
OKHttpUtil Overview
OKHttpUtil is a thin wrapper around Square's OkHttp library that simplifies HTTP requests for Java, Kotlin, Android, and server‑side use.
Features
Automatically selects HTTP or HTTPS based on the URL.
Cookies are recorded by default, enabling session‑preserving calls such as login.
Automatically handles 304 redirects and retries.
Supports proxy configuration.
Supports referer configuration.
Supports User‑Agent configuration.
Detects and decompresses Gzip responses.
Integrates with Spring Boot configuration files.
Provides a minimal API for one‑line calls.
Maven Dependency
<dependency>
<groupId>io.github.admin4j</groupId>
<artifactId>http</artifactId>
<version>0.4.0</version>
</dependency>Basic GET and POST
GET example:
Response response = HttpUtil.get("https://github.com/search", Pair.of("q", "okhttp"));
System.out.println("response = " + response);POST JSON example:
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 POST example:
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 Helper
When the response is JSON, 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 / 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", "...");
Response response = HttpUtil.upload("https://upload.qiniup.com/", formParams);
System.out.println(response);Download:
HttpUtil.down("https://gitee.com/admin4j/common-http", "path/");Fluent HttpRequest
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);Spring Boot Integration
Maven starter dependency:
<dependency>
<groupId>io.github.admin4j</groupId>
<artifactId>common-http-starter</artifactId>
<version>0.4.0</version>
</dependency>Configuration class example (log level, timeouts, connection pool, proxy, cookie handling):
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;
// 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;
}Wrapping External APIs – eBay Example
Base client sets common headers and base URL:
public class EbayClient extends ApiJsonClient {
public EbayClient(Long storeId) {
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 adds a method to fetch items:
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 builds a filter string and query map:
public class EbayOrderClient extends EbayClient {
public EbayOrderClient(Long storeId) { super(storeId); }
public JSONObject orders(String beginTime, String endTime, int limit, int offset) {
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 example:
EbayInventoryClient ebayInventoryClient = new EbayInventoryClient(1L);
JSONObject jsonObject = ebayInventoryClient.inventoryItem(0, 10);Source Code
Repository: https://github.com/admin4j/common-http
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
