✅ 常用 Java HTTP 客户端汇总及使用示例

news2025/6/7 5:17:56

在 Java 开发中,HTTP 客户端是与服务端交互的关键组件。随着技术发展,出现了多种 HTTP 客户端库,本文汇总了常用的 Java HTTP 客户端,介绍其特点、适用场景,并附上简单使用示例,方便开发者快速选择和上手。


1.常用 HTTP 客户端一览

名称简介特点
HttpClient(JDK 自带)Java 11 引入的官方 HTTP 客户端支持异步、HTTP/2,API 现代
RestTemplateSpring 提供的同步 HTTP 客户端(即将被淘汰)简洁,适合小项目;被 WebClient 替代
WebClientSpring 5 提供的响应式 HTTP 客户端支持响应式编程,推荐替代 RestTemplate
OkHttpClientSquare 出品,轻量级高性能 HTTP 客户端支持异步、连接池、拦截器
Apache HttpClientApache 出品的经典 HTTP 客户端库功能强大、稳定、支持各种高级特性
Feign声明式 HTTP 客户端,适用于 Spring Cloud开发效率高,集成 Ribbon/Hystrix
RetrofitSquare 出品,封装 OkHttp 的声明式客户端强大的 JSON 自动转换,适合 REST API
AsyncHttpClient异步非阻塞 HTTP 客户端(如 Netty 实现)高并发性能好,用于微服务场景
Vert.x WebClientVert.x 框架的异步 HTTP 客户端轻量级、响应式,非常适合微服务
Jetty HttpClientJetty 提供的 HTTP 客户端实现支持异步和 HTTP/2,常用于嵌入式


2.推荐选择场景

需求推荐客户端
简单同步请求RestTemplate(传统)或 HttpClient(Java 11+)
响应式或高并发WebClient, AsyncHttpClient, Vert.x WebClient
简洁封装、声明式调用Feign, Retrofit
高度可定制OkHttp, Apache HttpClient

3.各客户端 GET 和 POST 示例


1. HttpClient(Java 11+)

// GET 请求
HttpClient client = HttpClient.newHttpClient();

HttpRequest getRequest = HttpRequest.newBuilder()
        .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
        .GET()
        .build();

HttpResponse<String> getResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
System.out.println("GET response: " + getResponse.body());

// POST 请求
String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";

HttpRequest postRequest = HttpRequest.newBuilder()
        .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(json))
        .build();

HttpResponse<String> postResponse = client.send(postRequest, HttpResponse.BodyHandlers.ofString());
System.out.println("POST response: " + postResponse.body());

2. RestTemplate

RestTemplate restTemplate = new RestTemplate();

// GET 请求
String getResult = restTemplate.getForObject("https://jsonplaceholder.typicode.com/posts/1", String.class);
System.out.println("GET response: " + getResult);

// POST 请求
String url = "https://jsonplaceholder.typicode.com/posts";
Map<String, Object> postBody = new HashMap<>();
postBody.put("title", "foo");
postBody.put("body", "bar");
postBody.put("userId", 1);

String postResult = restTemplate.postForObject(url, postBody, String.class);
System.out.println("POST response: " + postResult);

3. WebClient

WebClient client = WebClient.create();

// GET 请求
client.get()
      .uri("https://jsonplaceholder.typicode.com/posts/1")
      .retrieve()
      .bodyToMono(String.class)
      .subscribe(response -> System.out.println("GET response: " + response));

// POST 请求
String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";

client.post()
      .uri("https://jsonplaceholder.typicode.com/posts")
      .header("Content-Type", "application/json")
      .bodyValue(json)
      .retrieve()
      .bodyToMono(String.class)
      .subscribe(response -> System.out.println("POST response: " + response));

4. OkHttpClient

OkHttpClient client = new OkHttpClient();

// GET 请求
Request getRequest = new Request.Builder()
        .url("https://jsonplaceholder.typicode.com/posts/1")
        .build();

Response getResponse = client.newCall(getRequest).execute();
System.out.println("GET response: " + getResponse.body().string());

// POST 请求
MediaType JSON = MediaType.get("application/json; charset=utf-8");
String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";

RequestBody body = RequestBody.create(json, JSON);
Request postRequest = new Request.Builder()
        .url("https://jsonplaceholder.typicode.com/posts")
        .post(body)
        .build();

Response postResponse = client.newCall(postRequest).execute();
System.out.println("POST response: " + postResponse.body().string());

5. Apache HttpClient

CloseableHttpClient client = HttpClients.createDefault();

// GET 请求
HttpGet getRequest = new HttpGet("https://jsonplaceholder.typicode.com/posts/1");
CloseableHttpResponse getResponse = client.execute(getRequest);
System.out.println("GET response: " + EntityUtils.toString(getResponse.getEntity()));

// POST 请求
HttpPost postRequest = new HttpPost("https://jsonplaceholder.typicode.com/posts");
postRequest.setHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}");
postRequest.setEntity(entity);

CloseableHttpResponse postResponse = client.execute(postRequest);
System.out.println("POST response: " + EntityUtils.toString(postResponse.getEntity()));

6. Feign

interface JsonPlaceholderClient {
    @RequestLine("GET /posts/1")
    String getPost();

    @RequestLine("POST /posts")
    @Headers("Content-Type: application/json")
    String createPost(String json);
}

JsonPlaceholderClient client = Feign.builder()
        .target(JsonPlaceholderClient.class, "https://jsonplaceholder.typicode.com");

// GET 请求
String getResponse = client.getPost();
System.out.println("GET response: " + getResponse);

// POST 请求
String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
String postResponse = client.createPost(json);
System.out.println("POST response: " + postResponse);

7. Retrofit

public interface ApiService {
    @GET("posts/1")
    Call<Post> getPost();

    @POST("posts")
    Call<Post> createPost(@Body Post post);
}

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://jsonplaceholder.typicode.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

ApiService service = retrofit.create(ApiService.class);

// GET 请求
service.getPost().enqueue(new Callback<Post>() {
    public void onResponse(Call<Post> call, Response<Post> response) {
        System.out.println("GET response: " + response.body());
    }
    public void onFailure(Call<Post> call, Throwable t) {
        t.printStackTrace();
    }
});

// POST 请求
Post newPost = new Post("foo", "bar", 1);
service.createPost(newPost).enqueue(new Callback<Post>() {
    public void onResponse(Call<Post> call, Response<Post> response) {
        System.out.println("POST response: " + response.body());
    }
    public void onFailure(Call<Post> call, Throwable t) {
        t.printStackTrace();
    }
});

8. AsyncHttpClient

AsyncHttpClient client = Dsl.asyncHttpClient();

// GET 请求
client.prepareGet("https://jsonplaceholder.typicode.com/posts/1")
      .execute()
      .toCompletableFuture()
      .thenAccept(response -> System.out.println("GET response: " + response.getResponseBody()))
      .join();

// POST 请求
String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";

client.preparePost("https://jsonplaceholder.typicode.com/posts")
      .setHeader("Content-Type", "application/json")
      .setBody(json)
      .execute()
      .toCompletableFuture()
      .thenAccept(response -> System.out.println("POST response: " + response.getResponseBody()))
      .join();

9. Vert.x WebClient

Vert.x 是一个轻量级、响应式的应用框架,其 WebClient 是异步非阻塞的 HTTP 客户端,非常适合高并发和微服务场景。

Vertx vertx = Vertx.vertx();
WebClient client = WebClient.create(vertx);

// GET 请求
client.getAbs("https://jsonplaceholder.typicode.com/posts/1")
      .send(ar -> {
          if (ar.succeeded()) {
              System.out.println("GET response: " + ar.result().bodyAsString());
          } else {
              ar.cause().printStackTrace();
          }
      });

// POST 请求
JsonObject json = new JsonObject()
        .put("title", "foo")
        .put("body", "bar")
        .put("userId", 1);

client.postAbs("https://jsonplaceholder.typicode.com/posts")
      .putHeader("Content-Type", "application/json")
      .sendJsonObject(json, ar -> {
          if (ar.succeeded()) {
              System.out.println("POST response: " + ar.result().bodyAsString());
          } else {
              ar.cause().printStackTrace();
          }
      });

10. Jetty HttpClient

Jetty 提供的 HTTP 客户端,支持异步和 HTTP/2,适合嵌入式和高性能场景。

HttpClient client = new HttpClient();
client.start();

// GET 请求
ContentResponse getResponse = client.GET("https://jsonplaceholder.typicode.com/posts/1");
System.out.println("GET response: " + getResponse.getContentAsString());

// POST 请求
Request postRequest = client.POST("https://jsonplaceholder.typicode.com/posts");
postRequest.header("Content-Type", "application/json");
postRequest.content(new StringContentProvider("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"));

ContentResponse postResponse = postRequest.send();
System.out.println("POST response: " + postResponse.getContentAsString());

client.stop();

4.结语

随着 Java 生态的发展,HTTP 客户端的选择也愈发丰富和多样。无论是 JDK 自带的现代 HttpClient,还是功能强大的第三方库如 OkHttp、Apache HttpClient,以及适合响应式编程的 WebClient,都各有优势,满足不同场景需求。

选择合适的 HTTP 客户端,能极大提升开发效率和应用性能。希望本文的汇总与示例,能帮助你快速掌握各类客户端的基本用法,并根据项目需求做出最佳选择。

如果你有更多使用心得或想了解更深入的高级功能,欢迎留言交流,我们一起成长!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2402503.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

快速用 uv 模拟发布一个 Python 依赖包到 TestPyPI 上,以及常用命令

目录 1. uv 介绍2. uv 安装&#xff08;Windows版&#xff09;3. 快速模拟一个要发布到TestPyPI上的依赖包&#xff0c;scoful-test-lib3.1 初始化 uv init3.2 进入scoful-test-lib3.3 修改pyproject.toml3.4 使用命令 uv sync3.5. 使用命令 uv lock3.6 使用命令 uv build3.7 获…

Python读取PDF:文本、图片与文档属性

在日常的数据采集、文档归档与信息挖掘过程中&#xff0c;PDF格式因其版式固定、内容稳定而被广泛使用。Python 开发者若希望实现 PDF 内容的自动化提取&#xff0c;选择一个易用且功能完善的库至关重要。本文将介绍如何用Python实现 PDF文本读取、图片提取 以及 文档属性读取 …

基于SpringBoot+Vue2的租房售房二手房小程序

角色&#xff1a; 管理员、房东、租客/买家 技术&#xff1a; springbootvue2mysqlmybatispagehelper 核心功能&#xff1a; 租房售房小程序是一个专注于房屋租赁和销售的综合性平台&#xff0c;基于SpringBootVue2MySQLMyBatisPageHelper技术栈开发&#xff0c;为用户提供…

基于本地LLM与MCP架构构建AI智能体全指南

一、AI智能体开发的新范式 随着人工智能技术的快速演进&#xff0c;AI智能体&#xff08;AI Agents&#xff09;正成为连接技术创新与实际应用的核心载体。从智能家居的温控系统到复杂的金融风控决策&#xff0c;AI智能体通过感知环境并执行目标导向的行为&#xff0c;正在重塑…

AT2659_GNSS低噪声放大器芯片

AT2659 射频放大器在SiGe工艺平台上实现23dB增益与0.71dB噪声系数的优异组合&#xff0c;专为BDS/GPS/GLONASS/GALILEO多模导航系统优化设计。其宽电压适应能力&#xff08;1.4-3.6V&#xff09;与低至4.4mA的功耗特性&#xff0c;配合1.5mm1mm0.55mm的6脚DFN封装&#xff08;R…

MADlib —— 基于 SQL 的数据挖掘解决方案(4)—— 数据类型之矩阵

目录 一、矩阵定义 二、MADlib 中的矩阵表示 1. 稠密 2. 稀疏 三、MADlib 中的矩阵运算函数 1. 矩阵操作函数分类 &#xff08;1&#xff09;表示函数 &#xff08;2&#xff09;计算函数 &#xff08;3&#xff09;提取函数 &#xff08;4&#xff09;归约函数&…

ServBay 1.13.0 更新,新增第三方反向代理/内网穿透

ServBay 作为一款简化本地开发环境搭建与管理的强大工具&#xff0c;致力于打造一个开箱即用、稳定可靠的本地开发平台&#xff0c;让用户专注于代码编写&#xff0c;提升开发效率。 ServBay 1.13.0 正式发布&#xff01;本次更新聚焦于提升本地开发项目的外部可访问性、增强国…

Docker构建自定义的镜像

构建自定义的 Docker 镜像是 Docker 使用中的核心操作之一。通过自定义镜像&#xff0c;你可以将应用程序及其依赖环境打包成一个可移植的容器化镜像。以下是详细的步骤和注意事项&#xff1a; 1. 准备工作 在构建自定义镜像之前&#xff0c;你需要准备以下内容&#xff1a; D…

【SSM】SpringMVC学习笔记8:拦截器

这篇学习笔记是Spring系列笔记的第8篇&#xff0c;该笔记是笔者在学习黑马程序员SSM框架教程课程期间的笔记&#xff0c;供自己和他人参考。 Spring学习笔记目录 笔记1&#xff1a;【SSM】Spring基础&#xff1a; IoC配置学习笔记-CSDN博客 对应黑马课程P1~P20的内容。 笔记2…

井川里予瓜pdf完整版

井川里予瓜pdf完整版 下载链接&#xff1a; 链接&#xff1a;https://pan.quark.cn/s/c75455d6be60 在网红文化盛行的当下&#xff0c;井川里予无疑是一位备受瞩目的人物。这位2001年出生于广东湛江的姑娘&#xff0c;凭借独特风格在网络世界掀起波澜&#xff0c;其发展轨迹…

基于 Zynq 平台的 EtherCAT 主站的软硬件协同设计

摘要: 针对工业自动化对控制能力和强实时性的需求&#xff0c;提出了一种基于 FPGA 的改进型 EtherCAT 硬件主站方案 。 该方案利用 Zynq&#xff0d;7000 平台&#xff0c;在 PL 端实现 FPGA 协议栈&#xff0c;以保证核心功能的高效执 行 。 基于 AXI4 总线设计…

聊一聊 .NET在Linux下的IO多路复用select和epoll

一&#xff1a;背景 1. 讲故事 在windows平台上&#xff0c;相信很多人都知道.NET异步机制是借助了Windows自带的 IO完成端口 实现的异步交互&#xff0c;那在 Linux 下.NET 又是怎么玩的呢&#xff1f;主要还是传统的 select&#xff0c;poll&#xff0c;epoll 的IO多路复用…

从零开始的嵌入式学习day33

网络编程及相关概念 UDP网络通信程序 UDP网络通信操作 一、网络编程及相关概念 1. 网络编程概念&#xff1a; 指通过计算机网络实现程序间通信的技术&#xff0c;涉及协议、套接字、数据传输等核心概念。常见的应用场景包括客户端-服务器模型、分布式系统、实时通信等。…

黑马Java面试笔记之框架篇(Spring、SpringMvc、Springboot)

一. 单例bean Spring框架中的单例bean是线程安全的吗&#xff1f; Spring框架中的bean是单例的&#xff0c;可以在注解Scope()进行设置 singleton&#xff1a;bean在每一个Spring IOC容器中只有一个实例。prototype&#xff1a;一个bean的定义可以有多个实例 总结 二. AOP AOP称…

全球IP归属地查询接口如何用C#进行调用?

一、什么是全球IP归属地查询接口 在全球化互联网时代&#xff0c;IP地址作为网络世界的地理位置标识&#xff0c;扮演着至关重要的角色。全球IP归属地查询接口通过解析IP地址&#xff0c;提供包括国家、省、市、区县和运营商在内的详细信息。 二、应用场景 1. 访问识别 全球…

NumPy 比较、掩码与布尔逻辑

文章目录 比较、掩码与布尔逻辑示例&#xff1a;统计下雨天数作为通用函数&#xff08;Ufuncs&#xff09;的比较运算符使用布尔数组计数条目布尔运算符 布尔数组作为掩码使用关键字 and/or 与运算符 &/| 的区别 比较、掩码与布尔逻辑 本文介绍如何使用布尔掩码来检查和操…

力扣HOT100之二分查找:35. 搜索插入位置

这道题属于是二分查找的入门题了&#xff0c;我依稀记得一些二分查找的编码要点&#xff0c;但是最后还是写出了一个死循环&#xff0c;无语(ˉ▽ˉ&#xff1b;)…又回去看了下自己当时的博客和卡哥的视频&#xff0c;这才发现自己分情况只分了两种&#xff0c;最后导致死循环…

使用API有效率地管理Dynadot域名,查看域名市场中所售域名的详细信息

关于Dynadot Dynadot是通过ICANN认证的域名注册商&#xff0c;自2002年成立以来&#xff0c;服务于全球108个国家和地区的客户&#xff0c;为数以万计的客户提供简洁&#xff0c;优惠&#xff0c;安全的域名注册以及管理服务。 Dynadot平台操作教程索引&#xff08;包括域名邮…

IM即时通讯软件,构建企业局域网内安全协作

安全与权限&#xff1a;协同办公的企业级保障 在协同办公场景中&#xff0c;BeeWorks 将安全机制贯穿全流程。文件在局域网内传输与存储时均采用加密处理&#xff0c;企业网盘支持水印预览、离线文档权限回收等功能&#xff0c;防止敏感资料外泄&#xff1b;多人在线编辑文档时…

VueScan:全能扫描,高清输出

在数字化办公和图像处理的领域&#xff0c;扫描仪扮演着不可或缺的角色。无论是文档的数字化存档、照片的高清复制&#xff0c;还是创意项目的素材采集&#xff0c;一款性能卓越、操作便捷的扫描软件能大幅提升工作效率和成果质量。VueScan正是这样一款集多功能于一身的扫描仪软…