当前位置: 首页 > news >正文

超级好用的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();}
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • shift 命令学习
  • 数据库客户端自定义驱动和数据源:以 HighGo-瀚高为例子
  • 如何分析软件测试中发现的Bug!
  • 快速掌握 ==== js 正则表达式
  • Unity 资源 之 战斗魔法咒语 - 第二卷(Combat Magic Spells - Volume II)
  • 2024年最新PyCharm保姆级安装教程
  • 算法训练(leetcode)第二十八天 | 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
  • 通过手机供网、可修改WIFI_MAC的网络设备
  • 相机光学(三十)——N5-N7-N8中性灰
  • UI图标库推荐网站
  • C++继承保姆级讲解下
  • 使用嵌入式知识打造智能手环:nRF52蓝牙开发实战(C++/BLE/传感器)
  • 超声波清洗机哪家好?家用超声波眼镜清洗机推荐
  • 关于共享盘(文件夹)
  • Hi3861鸿蒙开发环境搭建
  • GDB 调试 Mysql 实战(三)优先队列排序算法中的行记录长度统计是怎么来的(上)...
  • HashMap ConcurrentHashMap
  • iOS 颜色设置看我就够了
  • Laravel Mix运行时关于es2015报错解决方案
  • Making An Indicator With Pure CSS
  • Object.assign方法不能实现深复制
  • Spring-boot 启动时碰到的错误
  • 面试遇到的一些题
  • 如何合理的规划jvm性能调优
  • 深度学习在携程攻略社区的应用
  • 使用iElevator.js模拟segmentfault的文章标题导航
  • 手写双向链表LinkedList的几个常用功能
  • 提醒我喝水chrome插件开发指南
  • 限制Java线程池运行线程以及等待线程数量的策略
  • ######## golang各章节终篇索引 ########
  • #{}和${}的区别?
  • #Linux(权限管理)
  • (06)金属布线——为半导体注入生命的连接
  • (1)(1.13) SiK无线电高级配置(六)
  • (4)logging(日志模块)
  • (42)STM32——LCD显示屏实验笔记
  • (6)添加vue-cookie
  • (leetcode学习)236. 二叉树的最近公共祖先
  • (Note)C++中的继承方式
  • (阿里云万网)-域名注册购买实名流程
  • (安卓)跳转应用市场APP详情页的方式
  • (八)光盘的挂载与解挂、挂载CentOS镜像、rpm安装软件详细学习笔记
  • (附源码)基于SpringBoot和Vue的厨到家服务平台的设计与实现 毕业设计 063133
  • (论文阅读笔记)Network planning with deep reinforcement learning
  • (三)Kafka离线安装 - ZooKeeper开机自启
  • (算法)求1到1亿间的质数或素数
  • (微服务实战)预付卡平台支付交易系统卡充值业务流程设计
  • (自适应手机端)响应式新闻博客知识类pbootcms网站模板 自媒体运营博客网站源码下载
  • (自用)交互协议设计——protobuf序列化
  • ****** 二 ******、软设笔记【数据结构】-KMP算法、树、二叉树
  • .net core 6 使用注解自动注入实例,无需构造注入 autowrite4net
  • .NET DevOps 接入指南 | 1. GitLab 安装
  • .NET/C# 如何获取当前进程的 CPU 和内存占用?如何获取全局 CPU 和内存占用?
  • .net和jar包windows服务部署
  • .NET开发不可不知、不可不用的辅助类(三)(报表导出---终结版)