Mastering OKHttpUtil: Simplify Java HTTP Requests with Ready‑to‑Use Code
This article introduces the lightweight OKHttpUtil wrapper for Java and Kotlin, outlines its key features such as automatic protocol detection, cookie handling, proxy and header configuration, GZIP decompression, and Spring Boot integration, and provides comprehensive code examples for GET, POST, file upload, download, chained requests, and custom API client creation.
OKHttpUtil Features
Automatically determines HTTP or HTTPS based on the URL.
Cookies are recorded by default, enabling simulated login sessions.
Automatically handles 304 redirects and retries.
Supports proxy configuration.
Supports referer configuration.
Supports User-Agent configuration.
Automatically decompresses GZIP responses.
Supports Spring Boot configuration files.
Provides a minimalistic wrapper for easy invocation.
OKHttpUtil Usage
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
GET Request
The simplest GET request uses the HttpUtil class:
Response response = HttpUtil.get("https://github.com/search", Pair.of("q", "okhttp"));
System.out.println("response = " + response);POST Request
A one‑line POST request with JSON body:
Response post = HttpUtil.post(
"https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN",
"{\"msgtype\": \"text\",\"text\": {\"content\":\"【Feedback】Sample message\"}}");
System.out.println("post = " + post);
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
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 response = HttpUtil.upload("https://upload.qiniup.com/", formParams);
System.out.println(response);File Download
HttpUtil.down("https://gitee.com/admin4j/common-http", "path/");Chained Requests with HttpRequest
# GET example
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 example
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);Using OKHttpUtil in Spring Boot
Maven Dependency
<dependency>
<groupId>io.github.admin4j</groupId>
<artifactId>common-http-starter</artifactId>
<version>0.4.0</version>
</dependency>Spring Boot allows personalized OKHttp configuration via a configuration class:
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;
}
}Quickly Wrapping External APIs
Example: wrapping eBay APIs with a custom client.
public class EbayClient extends ApiJsonClient {
public EbayClient(Long storeId) {
// TODO fetch 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> queryMap = new HashMap(2);
queryMap.put("limit", limit);
queryMap.put("offset", offset);
return get("/sell/inventory/v1/inventory_item", queryMap);
}
}
EbayInventoryClient ebayInventoryClient = new EbayInventoryClient(1L);
JSONObject jsonObject = ebayInventoryClient.inventoryItem(0, 10);Similarly, an EbayOrderClient can be created to fetch order lists using appropriate query parameters.
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.
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
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.
