A Minimalist HTTP Client for Java: One‑Line External Requests with OKHttpUtil
This article introduces OKHttpUtil, a lightweight wrapper around OkHttp that lets Java developers perform HTTP GET, POST, file upload, download and Spring Boot integration with a single line of code, while offering features such as automatic HTTPS detection, cookie handling, proxy and GZIP support.
OKHttpUtil
OKHttpUtil provides a thin wrapper over Square's OkHttp library, offering a lightweight and easy‑to‑use HTTP client for Java and Kotlin.
Features
Automatically selects HTTP or HTTPS based on the URL.
Cookies are recorded by default, enabling simulated login flows.
Detects 304 redirects and follows them automatically.
Supports proxy configuration.
Allows custom User‑Agent headers.
Decompresses GZIP‑encoded responses.
Integrates with Spring Boot via a starter.
Provides a minimal one‑line invocation API.
Maven Dependency
<dependency>
<groupId>io.github.admin4j</groupId>
<artifactId>http</artifactId>
<version>0.4.0</version>
</dependency>Latest version: https://search.maven.org/artifact/io.github.admin4j/http
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] I am unique\"}}"
);
System.out.println("post = " + post);
# Form request
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 Handling
When the response is JSON, HttpJsonUtil returns a JSONObject directly:
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", "YOUR_TOKEN");
Response uploadResponse = HttpUtil.upload(
"https://upload.qiniup.com/",
formParams
);
System.out.println(uploadResponse);
// Download
HttpUtil.down(
"https://gitee.com/admin4j/common-http",
"path/"
);Spring Boot Integration
Add the starter dependency:
<dependency>
<groupId>io.github.admin4j</groupId>
<artifactId>common-http-starter</artifactId>
<version>0.4.0</version>
</dependency>Configure the client with a POJO:
public class HttpConfig {
private HttpLoggingInterceptor.Level loggLevel = HttpLoggingInterceptor.Level.BODY;
private long readTimeout = 30; // seconds
private long connectTimeout = 30; // seconds
private boolean followRedirects = false;
private int maxIdleConnections = 5;
private long keepAliveDuration = 5; // seconds
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;
}Chainable Requests with HttpRequest
# GET chain
Response r = HttpRequest.get("https://search.gitee.com/?skin=rec&type=repository")
.queryMap("q", "admin4j")
.header(HttpHeaderKey.USER_AGENT, "admin4j")
.execute();
System.out.println("response = " + r);
# POST form chain
Response r2 = 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 = " + r2);Quick External API Encapsulation
Example of wrapping eBay REST APIs with a base client and specialized subclasses.
public class EbayClient extends ApiJsonClient {
public EbayClient(Long storeId) {
// TODO: load store configuration
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> query = new HashMap<>(2);
query.put("limit", limit);
query.put("offset", offset);
return get("/sell/inventory/v1/inventory_item", query);
}
}
EbayInventoryClient client = new EbayInventoryClient(1L);
JSONObject json = client.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.
IoT Full-Stack Technology
Dedicated to sharing IoT cloud services, embedded systems, and mobile client technology, with no spam ads.
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.
