OKHttpUtil
In the world of Java, the HTTP client has long been dominated by Apache’s HttpClient. However, due to its large size and complex API, it is not widely used in many scenarios. While emerging libraries like OkHttp and Jodd-http are indeed user-friendly, they still come with a learning curve in certain situations.
Often, we seek a lightweight HTTP client that is simple and easy to use. OKHttp is a dependency library designed and developed by Square for handling HTTP network requests, and it is open-source. It can currently be used in both Java and Kotlin.
For Android apps, OkHttp has almost taken over all network request operations and is an essential choice for server-side requests to external interfaces. To simplify the use of OKHttp, OkHttpUtil provides a layer of encapsulation that makes HTTP requests incredibly simple.
Features of OKHttpUtil
- Automatically determines whether to request HTTP or HTTPS based on the URL, eliminating the need for extra code.
- By default, cookies are automatically recorded, allowing for simulated logins; after the first visit to the login URL, subsequent requests will maintain the login state.
- Automatically recognizes 304 redirects and makes a second request.
- Supports proxy configuration.
- Supports referer configuration.
- Supports User-Agent configuration.
- Automatically recognizes and decompresses Gzip formatted return content.
- Supports Spring Boot configuration files.
- Extremely simple encapsulation for calls.
Using OKHttpUtil
Maven inclusion
<dependency>
<groupId>io.github.admin4j</groupId>
<artifactId>http</artifactId>
<version>0.4.0</version>
</dependency>
Check for the latest version:
https://search.maven.org/artifact/io.github.admin4j/http
GET
The simplest usage is to quickly request an interface using the HttpUtil tool class:
Response response = HttpUtil.get(https://github.com/search, Pair.of(q, okhttp));
System.out.println(response = + response);
POST
One line of code is enough; of course, the POST request is also very simple:
# JSON format body
Response post = HttpUtil.post(https://oapi.dingtalk.com/robot/send?access_token=27f5954ab60ea8b2e431ae9101b1289c138e85aa6eb6e3940c35ee13ff8b6335, {\"msgtype\": \"text\",\"text\": {\"content\": \"【Feedback Reminder】I am who I am, a different kind of firework\"}});
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);
For responses in JSON format, you can use <span>HttpJsonUtil</span> to automatically 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
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-D4sCum-EvTIDYL-mEehwDtrSBg-Zca7t:qgOcR2gUoKmxt-VnsNb657Oatzo=:eyJzY29wZSI6InpoYW56aGkiLCJkZWFkbGluZSI6MTY2NTMwNzUxNH0=);
Response response=HttpUtil.upload(https://upload.qiniup.com/,formParams);
System.out.println(response);
File Download
HttpUtil.down(https://gitee.com/admin4j/common-http,path/);
HttpRequest Chained Requests
# GET
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
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);
POST form logs
16:49:14.092[main]DEBUG io.github.admin4j.http.core.HttpLogger- -->GET http://192.168.1.13:9100/auth/login?q=admin4j http/1.1
16:49:14.094[main]DEBUG io.github.admin4j.http.core.HttpLogger-User-Agent:admin4j
16:49:14.094[main]DEBUG io.github.admin4j.http.core.HttpLogger-Host:192.168.1.13:9100
16:49:14.094[main]DEBUG io.github.admin4j.http.core.HttpLogger-Connection:Keep-Alive
16:49:14.094[main]DEBUG io.github.admin4j.http.core.HttpLogger-Accept-Encoding:gzip
16:49:14.094[main]DEBUG io.github.admin4j.http.core.HttpLogger- -->END GET
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-<--200OK http://192.168.1.13:9100/auth/login?q=admin4j (575ms)
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-transfer-encoding:chunked
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Origin
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Access-Control-Request-Method
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Access-Control-Request-Headers
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Origin
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Access-Control-Request-Method
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Access-Control-Request-Headers
16:49:14.671[main]DEBUG io.github.admin4j.http.core.HttpLogger-Content-Type:application/json;charset=utf-8
16:49:14.671[main]DEBUG io.github.admin4j.http.core.HttpLogger-Date:Tue,08Nov 2022 08:49:14GMT
16:49:14.671[main]DEBUG io.github.admin4j.http.core.HttpLogger-
16:49:14.671[main]DEBUG io.github.admin4j.http.core.HttpLogger-{code:406,msg:Full authentication is required to access this resource}
16:49:14.671[main]DEBUG io.github.admin4j.http.core.HttpLogger-<--END HTTP(76-byte body)
response=Response{protocol=http/1.1,code=200,message=OK,url=http://192.168.1.13:9100/auth/login?q=admin4j}
Using in Spring Boot
Maven inclusion
<dependency>
<groupId>io.github.admin4j</groupId>
<artifactId>common-http-starter</artifactId>
<version>0.4.0</version>
</dependency>
Check for the latest version <span>io.github.admin4j:common-http-starter</span>
The Spring version allows for personalized configuration of OkHttp.
Configuration details can be found in
public class HttpConfig {
/**
* Log level
*/
private HttpLoggingInterceptor.Level loggLevel = HttpLoggingInterceptor.Level.BODY;
/**
* Read timeout in seconds
*/
private long readTimeout = 30;
/**
* Connection timeout
*/
private long connectTimeout = 30;
private boolean followRedirects = false;
/**
* Maximum number of connections
*/
private int maxIdleConnections = 5;
/**
* Maximum keep-alive duration in seconds
*/
private long keepAliveDuration = 5;
private String userAgent = "OKHTTP";
/**
* Whether to support cookies
*/
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;
}
}
How to Quickly Encapsulate External Interfaces
Taking a real project as an example, encapsulating the eBay interface
public class EbayClient extends ApiJsonClient {
/**
* Store configuration
*
* @param storeId
*/
public EbayClient(Long storeId) {
//TODO Get store-related 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));
}
}
<span>EbayClient</span> encapsulates the eBay API request base class
/**
* eBay inventory related API
* @author andanyang
*/
public class EbayInventoryClient extends EbayClient {
/**
* Store configuration
*
* @param storeId
*/
public EbayInventoryClient(Long storeId) {
super(storeId);
}
/**
* Inventory list
*
* @param limit
* @param offset
* @return
* @throws IOException
*/
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);
}
}
<span>EbayInventoryClient</span> encapsulates the eBay inventory API request
Usage
EbayInventoryClient ebayInventoryClient=new EbayInventoryClient(1L);
JSONObject jsonObject=ebayInventoryClient.inventoryItem(0,10);
/**
* Order related API
* @author andanyang
*/
public class EbayOrderClient extends EbayClient {
/**
* Store configuration
*
* @param storeId
*/
public EbayOrderClient(Long storeId) {
super(storeId);
}
/**
* Order list
*
* @param beginTime
* @param endTime
* @param limit
* @param offset
* @return
*/
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<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);
}
}
Using the <span>EbayInventoryClient</span> for inventory-related requests and the <span>EbayOrderClient</span> for order-related requests is quite clear.
Source code location:
https://github.com/admin4j/common-http
Source: andyoung.blog.csdn.net/article/details/127755025
👉 Click to receive the latest 2T+ free Java video learning materials>>
END
Premium materials, great benefits, free to receive
WeChatScan/Long press to identify Add 【Technical Exchange Group】 Daily sharing of premium learning materials in the group

Recently, I developed and organized a small program for quickly brushing up on interview questions《Interview Manual》【Click to use】; which includes thousands of common interview questions and answers (including basics, concurrency, JVM, MySQL, Redis, Spring, SpringMVC, SpringBoot, SpringCloud, message queues and many other types), welcome to use it.
This is the worst Controller layer code I have ever seen, no exceptions! Engineers who jumped from Alibaba write try-catch in such an elegant way!Running MySQL in Docker? Congratulations, you are about to be laid off.Changing the habit of checking for null != null takes only a second!This is what a backend API interface should look like! 666~Programmer exclusive navigation site (baoboxs.com), a one-stop shop for work, study, and entertainment!
👇👇
👇Click “Read the original text” to receive more materials (updating…)