超级好用的java http请求工具
kong-http
基于okhttp封装的轻量级http客户端
使用方式
Maven
<dependency><groupId>io.github.kongweiguang</groupId><artifactId>kong-http</artifactId><version>0.1</version>
</dependency>
Gradle
implementation 'io.github.kongweiguang:kong-http:0.1'
Gradle-Kotlin
implementation("io.github.kongweiguang:kong-http:0.1")
简单介绍
请求对象
public class ObjTest {@Testvoid test1() throws Exception {//自定义请求创建Req.of().method(Method.GET).url("http://localhost:8080/get");//基本的http请求Req.get("http://localhost:8080/get");Req.post("http://localhost:8080/post");Req.delete("http://localhost:8080/delete");Req.put("http://localhost:8080/put");Req.patch("http://localhost:8080/patch");Req.head("http://localhost:8080/head");Req.options("http://localhost:8080/options");Req.trace("http://localhost:8080/trace");Req.connect("http://localhost:8080/connect");//特殊http请求//application/x-www-form-urlencodedReq.formUrlencoded("http://localhost:8080/formUrlencoded");//multipart/form-dataReq.multipart("http://localhost:8080/multipart");//ws协议请求创建Req.ws("http://localhost:8080/ws");//sse协议请求创建Req.sse("http://localhost:8080/sse");}}
url请求地址
url添加有两种方式,可以混合使用,如果url和构建函数里面都有值,按构建函数里面为主
- 直接使用url方法
public class UrlTest {@Testvoid test1() throws Exception {final Res res = Req.get("http://localhost:8080/get/one/two").ok();System.out.println("res = " + res.str());}// 使用构建方法@Testvoid test2() {final Res res = Req.of().scheme("http").host("localhost").port(8080).path("get").path("one").path("two").ok();System.out.println("res.str() = " + res.str());// http://localhost:8080/get/one/two}//混合使用@Testvoid test3() throws Exception {// http://localhost:8080/get/one/twofinal Res res = Req.get("/get").scheme("http").host("localhost").port(8080).path("one").path("two").ok();System.out.println("res = " + res.str());}
}
url参数
public class UrlQueryTest {@Testvoid test1() throws Exception {//http://localhost:8080/get/one/two?q=1&k1=v1&k2=1&k2=2&k3=v3&k4=v4final Res res = Req.get("http://localhost:8080/get/one/two?q=1").query("k1", "v1").query("k2", Arrays.asList("1", "2")).query(new HashMap<String, String>() {{put("k3", "v3");put("k4", "v4");}}).ok();}}
请求头
设置请求头内容,cookie等
public class HeaderTest {@Testvoid test1() throws Exception {final Res res = Req.get("http://localhost:8080/header")//contentype.contentType(ContentType.json)//charset.charset(StandardCharsets.UTF_8)//user-agent.ua(Mac.chrome.v())//authorization.auth("auth qwe")//authorization bearer.bearer("qqq")//header.header("name", "value")//headers.headers(new HashMap<String, String>() {{put("name1", "value1");put("name2", "value2");}})//cookie.cookie("k", "v")//cookies.cookies(new HashMap<String, String>() {{put("k1", "v1");put("k2", "v2");}}).ok();System.out.println("res.str() = " + res.str());}}
请求体
get和head请求就算添加了请求体也不会携带在请求
public class BodyTest {@Testvoid test1() throws Exception {final User kkk = new User().setAge(12).setHobby(new String[]{"a", "b", "c"}).setName("kkk");final Res res = Req.post("http://localhost:8080/post_body")// .body(JSON.toJSONString(kkk))// .body("{}")//自动会将对象转成json对象,使用jackson.json(kkk)// .body("text", ContentType.text_plain).ok();System.out.println("res.str() = " + res.str());}}
form表单请求
可发送application/x-www-form-urlencoded表单请求,如果需要上传文件则使用multipart/form-data
public class FormTest {@Testvoid testForm() throws IOException {//application/x-www-form-urlencodedfinal Res ok = Req.formUrlencoded("http://localhost:8080/post_form").form("a", "1").form(new HashMap<String, String>() {{put("b", "2");}}).ok();System.out.println("ok.str() = " + ok.str());}@Testvoid test2() throws Exception {//multipart/form-datafinal Res ok = Req.multipart("http://localhost:8080/post_mul_form").file("k", "k.txt", Files.readAllBytes(Paths.get("D:\\k\\k.txt"))).form("a", "1").form(new HashMap<String, String>() {{put("b", "2");}}).ok();System.out.println("ok.str() = " + ok.str());}
}
异步请求
异步请求返回的是future,也可以使用join()或者get()方法等待请求执行完,具体使用请看CompletableFuture(异步编排)
public class AsyncTest {@Testvoid test1() throws Exception {final CompletableFuture<Res> future = Req.get("http://localhost:8080/get").query("a", "1").success(r -> System.out.println(r.str())).fail(System.out::println).okAsync();System.out.println("res = " + future.get(3, TimeUnit.SECONDS));}}
请求超时时间设置
超时设置的时间单位是秒
public class TimeoutTest {@Testvoid test1() throws Exception {final Res res = Req.get("http://localhost:8080/timeout").timeout(3)
// .timeout(10, 10, 10).ok();System.out.println(res.str());}}
响应对象
public class ResTest {@Testvoid testRes() {final Res res = Req.get("http://localhost:80/get_string").query("a", "1").query("b", "2").query("c", "3").ok();//返回值final String str = res.str();final byte[] bytes = res.bytes();final User obj = res.obj(User.class);final List<User> obj1 = res.obj(new TypeRef<List<User>>() {}.type());final List<String> list = res.list();final Map<String, String> map = res.map();final JSONObject jsonObject = res.jsonObj();final InputStream stream = res.stream();final Integer i = res.rInt();final Boolean b = res.rBool();//响应头final String ok = res.header("ok");final Map<String, List<String>> headers = res.headers();//状态final int status = res.code();//原始响应final Response response = res.raw();}}
重试
重试可以实现同步重试和异步重试,重试的条件可自定义实现
public class RetryTest {@Testvoid testRetry() {final Res res = Req.get("http://localhost:8080/error").query("a", "1").retry(3).ok();System.out.println("res = " + res.str());}@Testvoid testRetry2() {final Res res = Req.get("http://localhost:8080/error").query("a", "1").retry(3, Duration.ofSeconds(2), (r, t) -> {final String str = r.str();if (str.length() > 10) {return true;}return false;}).ok();System.out.println("res.str() = " + res.str());}@Testvoid testRetry3() {//异步重试final CompletableFuture<Res> res = Req.get("http://localhost:8080/error").query("a", "1").retry(3).okAsync();System.out.println(1);System.out.println("res.join().str() = " + res.join().str());}
}
请求代理
代理默认是http,可以设置socket代理
public class ProxyTest {@Testvoid test1() throws Exception {Config.proxy("127.0.0.1", 80);Config.proxy(Type.SOCKS, "127.0.0.1", 80);Config.proxyAuthenticator("k", "pass");final Res res = Req.get("http://localhost:8080/get/one/two").query("a", "1").ok();}}
下载
public class DowTest {@Testvoid testDow() {final Res ok = Req.get("http://localhost:80/get_file").ok();try {ok.file("d:\\k.txt");} catch (IOException e) {throw new RuntimeException(e);}}
}
添加日志
public class LogTest {@Testpublic void test() throws Exception {Req.get("http://localhost:8080/get/one/two").log(ReqLog.console, HttpLoggingInterceptor.Level.BODY).timeout(Duration.ofMillis(1000)).ok().then(r -> {System.out.println(r.code());System.out.println("ok -> " + r.isOk());}).then(r -> {System.out.println("redirect -> " + r.isRedirect());});}
}
ws请求
ws请求返回的res对象为null
public class WsTest {@Testvoid test() {final Res ok = Req.ws("ws://websocket/test").query("k", "v").wsListener(new WSListener() {@Overridepublic void open(final Req req, final Res res) {super.open(req, res);}@Overridepublic void msg(final Req req, final String text) {send("hello");}@Overridepublic void msg(final Req req, final byte[] bytes) {super.msg(req, bytes);}@Overridepublic void fail(final Req req, final Res res, final Throwable t) {super.fail(req, res, t);}@Overridepublic void closing(final Req req, final int code, final String reason) {super.closing(req, code, reason);}@Overridepublic void closed(final Req req, final int code, final String reason) {super.closed(req, code, reason);}}).ok();//res == nullUtil.sync(this);}}
sse请求
sse请求返回的res对象为null
public class SseTest {@Testvoid test() throws InterruptedException {Req.sse("localhost:8080/sse").sseListener(new SSEListener() {@Overridepublic void event(Req req, SseEvent msg) {System.out.println("sse -> " + msg.id());System.out.println("sse -> " + msg.type());System.out.println("sse -> " + msg.data());if (Objects.equals(msg.data(), "done")) {close();}}@Overridepublic void open(final Req req, final Res res) {super.open(req, res);}@Overridepublic void fail(final Req req, final Res res, final Throwable t) {super.fail(req, res, t);}@Overridepublic void closed(final Req req) {super.closed(req);}}).ok();Util.sync(this);}}
全局配置设置
public class ConfigTest {@Testvoid test1() throws Exception {//设置代理OK.conf().proxy("127.0.0.1", 80).proxy(Type.SOCKS, "127.0.0.1", 80).proxyAuthenticator("k", "pass")//设置拦截器.addInterceptor(new Interceptor() {@NotNull@Overridepublic Response intercept(@NotNull final Chain chain) throws IOException {System.out.println(1);return chain.proceed(chain.request());}})//设置连接池.connectionPool(new ConnectionPool(10, 10, TimeUnit.MINUTES))//设置异步调用的线程池.exec(Executors.newCachedThreadPool());}}
单次请求配置
public class SingingConfigTest {@Testpublic void test1() throws Exception {final Res res = Req.get("http://localhost:80/get_string").config(c -> c.followRedirects(false).ssl(false)).ok();}
}
相关文章:
超级好用的java http请求工具
kong-http 基于okhttp封装的轻量级http客户端 使用方式 Maven <dependency><groupId>io.github.kongweiguang</groupId><artifactId>kong-http</artifactId><version>0.1</version> </dependency>Gradle implementation …...

在原有的iconfont.css文件中加入新的字体图标
前言:在阿里图标库中,如果你没有这个字体图标的线上项目,那么你怎么在本地项目中的原始图标文件中添加新的图标呢? 背景:现有一个vue项目,下面是这个前端项目的字体图标文件。现在需要新开发功能页&#x…...

使用 ESP32-WROOM + DHT11 做个无屏温湿度计
最近梅雨天,有个房间湿度很大,而我需要远程查看温湿度,所以无所谓有没有显示屏,某宝上的温湿度计都是带屏的,如果连WIFI查看温湿度操作也比较麻烦,还需要换电池,实在不能满足我的需求࿰…...

如何使用 SwiftUI 构建 visionOS 应用
文章目录 前言WindowsVolumes沉浸式空间结论 前言 Apple Vision Pro 即将推出,现在是看看 SwiftUI API 的完美时机,这使我们能够将我们的应用程序适应 visionOS 提供的沉浸式世界。苹果表示,构建应用程序的最佳方式是使用 Swift 和 SwiftUI。…...

InspireFace-商用级的跨平台开源人脸分析SDK
InspireFace-商用级的跨平台开源人脸分析SDK InspireFaceSDK是由insightface开发的⼀款⼈脸识别软件开发⼯具包(SDK)。它提供了⼀系列功能,可以满⾜各种应⽤场景下的⼈脸识别需求,包括但不限于闸机、⼈脸⻔禁、⼈脸验证等。 该S…...
华为HCIP Datacom H12-821 卷24
1.单选题 企业大楼有大量员工通常都在上班时在大厅开始接入到公司的WLAN网络,随着每位员工走到各自的工位过程中,每个人的移动端叶通过漫游的方式漫游到各自的网络覆盖区域。为了尽量保证每个终端的IP地址是固定的,建议的做法是? A、配置VLAN Pool并配置顺序算法 B、…...

TikTok马来西亚直播网络怎么配置?
TikTok是一款全球流行的社交媒体应用,在东南亚地区拥有大量用户。在马来西亚这个多元化的国家,配置高效稳定的直播网络对TikTok的运营至关重要。 配置马来西亚直播网络的必要性 广泛的地理覆盖:马来西亚包括大片陆地和众多岛屿,网…...

基于若依的文件上传、下载
基于若依实现文件上传、下载 文章目录 基于若依实现文件上传、下载1、前端实现-文件上传1.1 通用上传分析1.2 修改实现上传接口 2、后端实现-文件上传3、后端实现-文件下载4、前端实现-文件下载 官网其实也写了,但是我是自己改造封装了一下,再次迈向全栈…...

论文回顾 | CVPR 2021 | How to Calibrate Your Event Camera | 基于图像重建的事件相机校准新方法
论文速览 | CVPR 2021 | How to Calibrate Your Event Camera | 基于图像重建的事件相机校准新方法 1 引言 在计算机视觉和机器人领域,相机校准一直是一个基础而又重要的问题。传统的相机校准方法主要依赖于从已知校准图案中提取角点,然后通过优化算法求解相机的内参和外参。这…...
高级java每日一道面试题-2024年7月1日
题目:请解释 Java 中的内存泄漏,并说明如何检测和避免内存泄漏。 答案: 内存泄漏指的是程序中不再使用的对象,由于某些原因没有被垃圾回收器回收,仍然占据着内存空间,导致可用内存逐渐减少,最…...

当需要对多个表进行联合更新操作时,怎样确保数据的一致性?
文章目录 一、问题分析二、解决方案三、示例代码(以 MySQL 为例)四、加锁机制示例五、测试和验证六、总结 在数据库管理中,经常会遇到需要对多个表进行联合更新的情况。这种操作带来了一定的复杂性,因为要确保在整个更新过程中数据…...
数据结构-线性表的应用
目录 前言一、有序表的合并1.1 顺序表实现1.2 单链表实现 二、稀疏多项式的相加和相乘2.1 稀疏多项式的相加2.2 稀疏多项式的相乘 总结 前言 本篇文章介绍线性表的应用,分别使用顺序表和单链表实现有序表的合并,最后介绍如何使用单链表实现两个稀疏多项…...
cpp http server/client
httplib 使用httplib库 basedemo server.cpp #include "httplib.h" #include <iostream> using namespace httplib;int main(void) {Server svr;svr.Get("/hello", [](const Request& req, Response& res) {std::cout << "lo…...

昇思25天学习打卡营第2天|MindSpore快速入门
打卡 目录 打卡 快速入门案例:minist图像数据识别任务 案例任务说明 流程 1 加载并处理数据集 2 模型网络构建与定义 3 模型约束定义 4 模型训练 5 模型保存 6 模型推理 相关参考文档入门理解 MindSpore数据处理引擎 模型网络参数初始化 模型优化器 …...

django之url路径
方式一:path 语法:<<转换器类型:自定义>> 作用:若转换器类型匹配到对应类型的数据,则将数据按照关键字传参的方式传递给视图函数 类型: str: 匹配除了”/“之外的非空字符串。 /test/zvxint: 匹配0或任何…...

【OnlyOffice】桌面应用编辑器,插件开发大赛,等你来挑战
OnlyOffice,桌面应用编辑器,最近版本已从8.0升级到了8.1 从PDF、Word、Excel、PPT等全面进行了升级。随着AI应用持续的火热,OnlyOffice也在不断推出AI相关插件。 因此,在此给大家推荐一下OnlyOffice本次的插件开发大赛。 详细信息…...

[学习笔记]SQL学习笔记(连载中。。。)
学习视频:【数据库】SQL 3小时快速入门 #数据库教程 #SQL教程 #MySQL教程 #database#Python连接数据库 目录 1.SQL的基础知识1.1.表(table)和键(key)1.2.外键、联合主键 2.MySQL安装(略,请自行参考视频)3.基本的MySQL语法3.1.规…...

Buuctf之SimpleRev做法
首先,查个壳,64bit,那就丢进ida64中进行反编译进来之后,我们进入main函数,发现里面没什么东西,那就shiftf12搜索字符串,找到关键字符串,双击进入然后再选中该字符串,ctrl…...

【云原生监控】Prometheus 普罗米修斯从搭建到使用详解
目录 一、前言 二、服务监控概述 2.1 什么是微服务监控 2.2 微服务监控指标 2.3 微服务监控工具 三、Prometheus概述 3.1 Prometheus是什么 3.2 Prometheus 特点 3.3 Prometheus 架构图 3.3.1 Prometheus核心组件 3.3.2 Prometheus 工作流程 3.4 Prometheus 应用场景…...

【C++】模板进阶--保姆级解析(什么是非类型模板参数?什么是模板的特化?模板的特化如何应用?)
目录 一、前言 二、什么是C模板? 💦泛型编程的思想 💦C模板的分类 三、非类型模板参数 ⚡问题引入⚡ ⚡非类型模板参数的使用⚡ 🔥非类型模板参数的定义 🔥非类型模板参数的两种类型 ὒ…...

深入浅出Asp.Net Core MVC应用开发系列-AspNetCore中的日志记录
ASP.NET Core 是一个跨平台的开源框架,用于在 Windows、macOS 或 Linux 上生成基于云的新式 Web 应用。 ASP.NET Core 中的日志记录 .NET 通过 ILogger API 支持高性能结构化日志记录,以帮助监视应用程序行为和诊断问题。 可以通过配置不同的记录提供程…...
云原生核心技术 (7/12): K8s 核心概念白话解读(上):Pod 和 Deployment 究竟是什么?
大家好,欢迎来到《云原生核心技术》系列的第七篇! 在上一篇,我们成功地使用 Minikube 或 kind 在自己的电脑上搭建起了一个迷你但功能完备的 Kubernetes 集群。现在,我们就像一个拥有了一块崭新数字土地的农场主,是时…...
逻辑回归:给不确定性划界的分类大师
想象你是一名医生。面对患者的检查报告(肿瘤大小、血液指标),你需要做出一个**决定性判断**:恶性还是良性?这种“非黑即白”的抉择,正是**逻辑回归(Logistic Regression)** 的战场&a…...
三维GIS开发cesium智慧地铁教程(5)Cesium相机控制
一、环境搭建 <script src"../cesium1.99/Build/Cesium/Cesium.js"></script> <link rel"stylesheet" href"../cesium1.99/Build/Cesium/Widgets/widgets.css"> 关键配置点: 路径验证:确保相对路径.…...

OPENCV形态学基础之二腐蚀
一.腐蚀的原理 (图1) 数学表达式:dst(x,y) erode(src(x,y)) min(x,y)src(xx,yy) 腐蚀也是图像形态学的基本功能之一,腐蚀跟膨胀属于反向操作,膨胀是把图像图像变大,而腐蚀就是把图像变小。腐蚀后的图像变小变暗淡。 腐蚀…...
【Java学习笔记】BigInteger 和 BigDecimal 类
BigInteger 和 BigDecimal 类 二者共有的常见方法 方法功能add加subtract减multiply乘divide除 注意点:传参类型必须是类对象 一、BigInteger 1. 作用:适合保存比较大的整型数 2. 使用说明 创建BigInteger对象 传入字符串 3. 代码示例 import j…...

使用Spring AI和MCP协议构建图片搜索服务
目录 使用Spring AI和MCP协议构建图片搜索服务 引言 技术栈概览 项目架构设计 架构图 服务端开发 1. 创建Spring Boot项目 2. 实现图片搜索工具 3. 配置传输模式 Stdio模式(本地调用) SSE模式(远程调用) 4. 注册工具提…...

代码规范和架构【立芯理论一】(2025.06.08)
1、代码规范的目标 代码简洁精炼、美观,可持续性好高效率高复用,可移植性好高内聚,低耦合没有冗余规范性,代码有规可循,可以看出自己当时的思考过程特殊排版,特殊语法,特殊指令,必须…...

【Linux系统】Linux环境变量:系统配置的隐形指挥官
。# Linux系列 文章目录 前言一、环境变量的概念二、常见的环境变量三、环境变量特点及其相关指令3.1 环境变量的全局性3.2、环境变量的生命周期 四、环境变量的组织方式五、C语言对环境变量的操作5.1 设置环境变量:setenv5.2 删除环境变量:unsetenv5.3 遍历所有环境…...

DeepSeek源码深度解析 × 华为仓颉语言编程精粹——从MoE架构到全场景开发生态
前言 在人工智能技术飞速发展的今天,深度学习与大模型技术已成为推动行业变革的核心驱动力,而高效、灵活的开发工具与编程语言则为技术创新提供了重要支撑。本书以两大前沿技术领域为核心,系统性地呈现了两部深度技术著作的精华:…...