超级好用的java http请求工具

news/2024/9/18 12:48:24/ 标签: java, http, iphone
http://www.w3.org/2000/svg" style="display: none;">

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")

简单介绍

请求对象

java">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方法
java">
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参数

java">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等

java">
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请求就算添加了请求体也不会携带在请求

java">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

java">
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(异步编排)

java">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));}}

请求超时时间设置

超时设置的时间单位是

java">
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());}}

响应对象

java">
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();}}

重试

重试可以实现同步重试和异步重试,重试的条件可自定义实现

java">
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代理

java">
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();}}

下载

java">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);}}
}

添加日志

java">
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

java">
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

java">
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);}}

全局配置设置

java">
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());}}

单次请求配置

java">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();}
}

http://www.ppmy.cn/news/1474659.html

相关文章

独特功能的视频号矩阵系统源码,支持多短视频平台自动发布和定时发布

在短视频行业竞争日趋激烈的今天&#xff0c;一个高效的视频发布系统对于内容创作者和营销团队来说至关重要。视频号矩阵系统源码以其独特的功能&#xff0c;为多平台自动发布和定时发布提供了强大的技术支持。 多平台自动化发布&#xff1a;无缝内容分发 视频号矩阵系统源码…

掌握MOJO命令行:参数解析的艺术

在软件开发中&#xff0c;命令行接口&#xff08;CLI&#xff09;是一种与程序交互的强大方式&#xff0c;它允许用户通过终端输入指令和参数来控制程序的行为。对于MOJO语言&#xff0c;即使它是一个假想的编程语言&#xff0c;我们也可以设想它具备解析命令行参数的能力。本文…

Oracle执行一条SQL的内部过程

一、SQL语句根据其功能主要可以分为以下几大类&#xff1a; 1. 数据查询语言&#xff08;DQL, Data Query Language&#xff09; 功能&#xff1a;用于从数据库中检索数据&#xff0c;常用于查询表中的记录。基本结构&#xff1a;主要由SELECT子句、FROM子句、WHERE子句等组成…

使用Docker、Docker-compose部署单机版达梦数据库(DM8)

安装前准备 Linux Centos7安装&#xff1a;https://blog.csdn.net/andyLyysh/article/details/127248551?spm1001.2014.3001.5502 Docker、Docker-compose安装&#xff1a;https://blog.csdn.net/andyLyysh/article/details/126738190?spm1001.2014.3001.5502 下载DM8镜像 …

Bilibili Android一二面凉经(2024)

BiliBili Android一二面凉经(2024) 笔者作为一名双非二本毕业7年老Android, 最近面试了不少公司, 目前已告一段落, 整理一下各家的面试问题, 打算陆续发布出来, 供有缘人参考。今天给大家带来的是《BiliBili Android一二面凉经(2024)》。 面试职位: 高级Android开发工程师&…

Openresty+lua 定时函数 ngx.timer.every

ngx.timer.every 是 OpenResty 中的一个函数&#xff0c;用于创建定时器&#xff0c;以便定期执行某个函数或代码块。它的用法如下&#xff1a; local delay 5 -- 定时器间隔时间&#xff0c;单位为秒ngx.timer.every(delay, function(premature)-- 这里是定时执行的代码块i…

2.5 C#视觉程序开发实例1----CamManager实现模拟相机采集图片(Form_Vision部分代码)

2.5 C#视觉程序开发实例1----CamManager实现模拟相机采集图片(Form_Vision部分代码) 1 目标效果视频 CamManager 2 增加一个class IMG_BUFFER 用来管理采集的图片 // <summary> /// IMG_BUFFER 用来管理内存图片的抓取队列 /// </summary> public class IMG_BUFF…

【代码随想录算法训练营第六十二天|卡码网53.寻宝(prim算法和kruskal算法)】

文章目录 53.寻宝prim算法kruskal算法 53.寻宝 prim算法 prim算法三部曲&#xff1a; 1.选择当前最短入树结点&#xff1b;2.更新入树结点&#xff1b;3.更新结点距离最小生成树的距离。 可以把所有已经使用过的结点看作一个整体&#xff0c;然后把他们相接的结点的结点顶点边…

百日筑基第十八天-一头扎进消息队列1

百日筑基第十八天-一头扎进消息队列1 先对业界消息队列有个宏观的认识 消息队列的现状 当前开源社区用的较多的消息队列主要有 RabbitMQ、RocketMQ、Kafka 和Pulsar 四款。 国内大厂也一直在自研消息队列&#xff0c;比如阿里的 RocketMQ、腾讯的 CMQ 和 TubeMQ、京东的 JM…

玄机——第五章 linux实战-CMS01 wp

文章目录 一、前言二、概览简介 三、参考文章四、步骤&#xff08;解析&#xff09;准备步骤#1.0步骤#1.1通过本地 PC SSH到服务器并且分析黑客的 IP 为多少,将黑客 IP 作为 FLAG 提交; 步骤#1.2通过本地 PC SSH到服务器并且分析黑客修改的管理员密码(明文)为多少,将黑客修改的…

Perl 语言开发(八):子程序和模块

目录 1. 引言 2. 子程序的基本概念与用法 2.1 子程序的定义和调用 2.2 传递参数 2.3 返回值 2.4 上下文和返回值 3. 模块的基本概念与用法 3.1 模块的定义 3.2 使用模块 3.3 导出符号 3.4 模块的文件结构和命名 4. 实际应用中的子程序与模块 4.1 子程序参数验证与…

省市县下拉框的逻辑以及多表联查的实例

2024.7.12 一. 省市县的逻辑开发。1、准备&#xff1a;1.1. 要求&#xff1a;1.2 数据库表&#xff1a; 2. 逻辑&#xff1a;3. 方法3.1 创建实体类3.2 数据访问层3.3 实现递归方法3.4 控制器实现3.5 前端处理 二、多表联查&#xff08;给我干红温了&#xff09;1. 出现了问题2…

代理详解之静态代理、动态代理、SpringAOP实现

1、代理介绍 代理是指一个对象A通过持有另一个对象B&#xff0c;可以具有B同样的行为的模式。为了对外开放协议&#xff0c;B往往实现了一个接口&#xff0c;A也会去实现接口。但是B是“真正”实现类&#xff0c;A则比较“虚”&#xff0c;他借用了B的方法去实现接口的方法。A…

服务网格新篇章:Eureka与分布式服务网格的协同共舞

服务网格新篇章&#xff1a;Eureka与分布式服务网格的协同共舞 引言 在微服务架构的浪潮中&#xff0c;服务网格&#xff08;Service Mesh&#xff09;技术以其微服务间通信的精细化控制而备受瞩目。Eureka作为Netflix开源的服务发现框架&#xff0c;虽然本身不直接提供服务网…

前端面试题47(在动态控制路由时,如何防止未授权用户访问受保护的页面?)

在Vue中&#xff0c;防止未授权用户访问受保护页面通常涉及到使用路由守卫&#xff08;Route Guards&#xff09;。路由守卫允许你在路由发生改变前或后执行一些逻辑&#xff0c;比如检查用户是否已登录或者有访问某个页面的权限。下面是一些常见的路由守卫类型及其使用方式&am…

C++相关概念和易错语法(19)(继承规则、继承下的构造和析构、函数隐藏)

1.继承规则 继承的本质是复用&#xff0c;是结构上的继承而不是内容上的继承&#xff0c;近似于在子类中声明了父类的成员变量。 &#xff08;1&#xff09;写法&#xff1a;class student : public person 派生类&#xff08;子类&#xff09;&#xff0c;继承方式&…

数据库doris中的tablet底层解析

在Doris中,tablet(数据片)是数据存储和管理的最小单元。理解tablet的底层原理有助于更好地理解Doris的高可用性、负载均衡和查询优化等特性。 Tablet 的概念 Tablet:Tablet是Doris中用于存储数据的最小物理单元。每个tablet通常对应于一个数据分区和一个分桶组合的子集。…

网工内推 | 网络运维、云计算工程师,NP以上认证,平均薪资10K

01 网络运维 &#x1f537;岗位职责 1、至少3年以上的网络运维相关工作经验; 2、熟悉VLAN、STP、OSPF、RIP、BGP等网络技术; 3、熟悉IPsec、SSL等VPN技术; 4、熟悉主流网络安全厂商的各种产品; 5、精通TCP/IP协议&#xff0c;熟悉主流网络产品设备的调试、配置方法: 6、有…

人工智能笔记分享

文章目录 人工智能图灵测试分类分类与聚类的区别&#xff08;重点&#xff09;分类 (Classification)聚类 (Clustering) 特征提取 分类器&#xff08;重点&#xff09;特征提取为什么要进行特征提取&#xff1f;&#xff08;重点&#xff09;分类器 训练集、测试集大小&#x…

Spring Boot与Jenkins的集成

Spring Boot与Jenkins的集成 大家好&#xff0c;我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编&#xff0c;也是冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01; 一、引言 Jenkins作为一个开源的持续集成&#xff08;CI&#xff09;和持续交付…