Java HTTP client常见库

前言

每种编程语言里最常用的库恐怕是Http请求库了,如python里的requests包,nodejs里的request模块。

在Java世界里,也是百花齐放,山头林立。常用的有:

  • HttpURLConnection: 最早的JDK提供的类
  • Java 11提供的HttpClient
  • Apache HttpComponents项目中的HTTPClient
  • Square提供的OkHttpClient
  • Spring 自带的WebClient

Apache HttpComponents

该组件提供了两个核心类:

  • HttpCore: 更底层的传输处理类
  • HttpClient:基于HttpCore实现的HTTP-compliant 处理类

JDK 11+ HTTP Client使用举例

Post同步的json数据:

java 复制代码
public void invokePost() {
  
  try {
   String requestBody = prepareRequest();
   HttpClient client = HttpClient.newHttpClient();
   HttpRequest request = HttpRequest
     .newBuilder()
     .uri(URI.create("https://reqbin.com/echo/post/json"))
     .POST(HttpRequest.BodyPublishers.ofString(requestBody))
     .header("Accept", "application/json")
     .build();

   HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

   System.out.println(response.body());
  } catch (IOException | InterruptedException e) {
   e.printStackTrace();
  }
 }

 private String prepareRequest() throws JsonProcessingException {
  var values = new HashMap<String, String>() {
   {
    put("Id", "12345");
    put("Customer", "Roger Moose");
    put("Quantity", "3");
    put("Price","167.35");
   }
  };

  var objectMapper = new ObjectMapper();
  String requestBody = objectMapper.writeValueAsString(values);
  return requestBody;
 }

发送异步请求:

java 复制代码
public void invoke() throws URISyntaxException {
  
  HttpClient client = HttpClient.newBuilder()
      .version(Version.HTTP_2)
      .followRedirects(Redirect.NORMAL)
      .build();
  
  HttpRequest request = HttpRequest.newBuilder()
     .uri(new URI(URLConstants.URL))
     .GET()
     .header(URLConstants.API_KEY_NAME, URLConstants.API_KEY_VALUE)
     .timeout(Duration.ofSeconds(10))
     .build();
  
  
  client.sendAsync(request, BodyHandlers.ofString())
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println)
    .join();
 }

HTTP Client包装库

cVurl

cVurl is an open-source wrapper for the Java HTTP client. It is written in Java 11 and can be used with any JDK 11.0.2 or newer.

java 复制代码
public void cVurl() {
    CVurl cVurl = new CVurl();

    //POST
    Result result = cVurl.post("https://api.imgflip.com/caption_image")
        .queryParams(Map.of(
                "template_id", "112126428",
        "username", "test-user",
        "password", "123test321",
        "text0", "text0",
        "text1", "text1"
        ))
        .asObject(Result.class);

    System.out.println("CVurl POST: " + result);
}

它支持Compression、Multipart、Form data这些Java 11 HttpClient不具备的特性。

Avaje-HTTP

  • Fluid API for building URLs and payload
  • JSON marshaling using Avaje Jsonb/Jackson/Gson
  • Light Feign-style interfaces via annotation processing.
  • Request/Response Interception
  • Authorization via Basic Auth or OAuth Bearer Tokens
  • Async and sync API

个人建议

在实际项目中,设计符合自身项目需求的HTTP client接口,并基于JDK 11 HTTP client实现,独立于任何上述库。

参考链接

相关推荐
L2ncE8 分钟前
高并发场景数据与一致性的简单思考
java·后端·架构
武昌库里写JAVA9 分钟前
使用 Java 开发 Android 应用:Kotlin 与 Java 的混合编程
java·vue.js·spring boot·sql·学习
小指纹9 分钟前
河南萌新联赛2025第(六)场:郑州大学
java·开发语言·数据结构·c++·算法
叶~璃12 分钟前
云计算:企业数字化转型的核心引擎
java
码luffyliu26 分钟前
MySQL:MVCC机制及其在Java秋招中的高频考点
java·数据库·mysql·事务·并发·mvcc
程序员鱼皮27 分钟前
这套 Java 监控系统太香了!我连夜给项目加上了
java·前端·ai·程序员·开发·软件开发
岁忧37 分钟前
(nice!!!)(LeetCode 每日一题) 1277. 统计全为 1 的正方形子矩阵 (动态规划)
java·c++·算法·leetcode·矩阵·go·动态规划
律品1 小时前
pytest的前置与后置
开发语言·python·pytest
S妖O风F1 小时前
IDEA报JDK版本问题
java·ide·intellij-idea
Mr. Cao code1 小时前
使用Tomcat Clustering和Redis Session Manager实现Session共享
java·linux·运维·redis·缓存·tomcat