超级好用的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 {

    @Test
    void 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-urlencoded
        Req.formUrlencoded("http://localhost:8080/formUrlencoded");
        //multipart/form-data
        Req.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 {

    @Test
    void test1() throws Exception {
        final Res res = Req.get("http://localhost:8080/get/one/two").ok();
        System.out.println("res = " + res.str());
    }


    // 使用构建方法
    @Test
    void 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
    }

    //混合使用
    @Test
    void test3() throws Exception {
        // http://localhost:8080/get/one/two
        final 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 {

    @Test
    void test1() throws Exception {
        //http://localhost:8080/get/one/two?q=1&k1=v1&k2=1&k2=2&k3=v3&k4=v4
        final 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 {

    @Test
    void 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 {

    @Test
    void 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 {

    @Test
    void testForm() throws IOException {
        //application/x-www-form-urlencoded
        final 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());
    }

    @Test
    void test2() throws Exception {
        //multipart/form-data
        final 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 {

    @Test
    void 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 {

    @Test
    void 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 {

    @Test
    void 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 {

    @Test
    void testRetry() {
        final Res res = Req.get("http://localhost:8080/error")
                .query("a", "1")
                .retry(3)
                .ok();
        System.out.println("res = " + res.str());
    }

    @Test
    void 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());
    }

    @Test
    void 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 {

    @Test
    void 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 {

    @Test
    void 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 {
    @Test
    public 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 {

    @Test
    void test() {

        final Res ok = Req.ws("ws://websocket/test")
                .query("k", "v")
                .wsListener(new WSListener() {
                    @Override
                    public void open(final Req req, final Res res) {
                        super.open(req, res);
                    }

                    @Override
                    public void msg(final Req req, final String text) {
                        send("hello");
                    }

                    @Override
                    public void msg(final Req req, final byte[] bytes) {
                        super.msg(req, bytes);
                    }

                    @Override
                    public void fail(final Req req, final Res res, final Throwable t) {
                        super.fail(req, res, t);
                    }

                    @Override
                    public void closing(final Req req, final int code, final String reason) {
                        super.closing(req, code, reason);
                    }

                    @Override
                    public void closed(final Req req, final int code, final String reason) {
                        super.closed(req, code, reason);
                    }
                })
                .ok();
        //res == null
        Util.sync(this);
    }

}

sse请求

sse请求返回的res对象为null


public class SseTest {


    @Test
    void test() throws InterruptedException {

        Req.sse("localhost:8080/sse")
                .sseListener(new SSEListener() {
                    @Override
                    public 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();
                        }
                    }

                    @Override
                    public void open(final Req req, final Res res) {
                        super.open(req, res);
                    }

                    @Override
                    public void fail(final Req req, final Res res, final Throwable t) {
                        super.fail(req, res, t);
                    }

                    @Override
                    public void closed(final Req req) {
                        super.closed(req);
                    }
                })
                .ok();

        Util.sync(this);
    }

}

全局配置设置


public class ConfigTest {

    @Test
    void 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
                    @Override
                    public 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 {
    @Test
    public void test1() throws Exception {
        final Res res = Req.get("http://localhost:80/get_string")
                .config(c -> c.followRedirects(false).ssl(false))
                .ok();
    }
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Ubuntu + SSH密钥连接服务器

1. 下载VS code cd到下载文件夹后&#xff0c;使用命令安装&#xff0c;把xxx复制为文件名 sudo dpkg -i xxx.deb2. 为VSCode换皮肤 3. 下载SSH插件和Docker插件 4. 配置SSH 把密钥key文件放在/home/your_user_name/.ssh/里面&#xff0c;然后在/home/your_user_name/.ssh/c…

第1集《修习止观坐禅法要》

《修习止观坐禅法要》诸位法师&#xff0c;诸位学员&#xff0c;阿弥院佛&#xff01; 我们今天能够暂时放下世间的尘劳&#xff0c;大家在一起研究佛法的课程&#xff0c;这件事情在我们的生命当中是非常的稀有难得。 基本上&#xff0c;我们佛法的修习目的是追求身心的安乐…

基于vue的3D高德地图的引入

在引入高德地图的时候需要先注册一个账号 登录下面的网站 账号认证 | 高德控制台 (amap.com) 打开首页应用管理&#xff0c;我的应用 创建新的应用 根据自己的需求进行选择 创建完成之后&#xff0c;点击添加key 不同的服务平台对应不同的可使用服务&#xff0c;选择自己适…

3.js - 模板渲染 - 金属切面效果

md&#xff0c;狗不学&#xff0c;我学 源码 // ts-nocheck// 引入three.js import * as THREE from three// 导入轨道控制器 import { OrbitControls } from three/examples/jsm/controls/OrbitControls// 导入lil.gui import { GUI } from three/examples/jsm/libs/lil-gui.m…

机器学习与深度学习:区别(含工作站硬件推荐)

一、机器学习与深度学习区别 机器学习&#xff08;ML&#xff1a;Machine Learning&#xff09;与深度学习&#xff08;DL&#xff1a;Deep Learning&#xff09;是人工智能&#xff08;AI&#xff09;领域内两个重要但不同的技术。它们在定义、数据依赖性以及硬件依赖性等方面…

如何在忘记密码的情况下解锁Android手机?

您的 Android 设备密码有助于保护您的数据并防止您的个人信息被滥用。但是&#xff0c;如果您被锁定在Android设备之外怎么办&#xff1f;我们知道忘记您的 Android 手机密码是多么令人沮丧&#xff0c;因为它会导致您的设备和数据无法访问。在本技术指南中&#xff0c;我们将向…

[图解]企业应用架构模式2024新译本讲解23-标识映射2

1 00:00:00,950 --> 00:00:02,890 好&#xff0c;我们往下走 2 00:00:04,140 --> 00:00:04,650 一样的 3 00:00:04,660 --> 00:00:07,170 这前面也见过了&#xff0c;定义一个对象数组 4 00:00:07,870 --> 00:00:12,820 数组的长度就是字段的数量&#xff0c;4个…

学IT上培训班真的有用吗?

在学习IT技术的过程中&#xff0c;你是否也被安利过各种五花八门的技术培训班&#xff1f;这些培训班都是怎样向你宣传的&#xff0c;你又对此抱有着怎样的态度呢&#xff1f;在培训班里学技术&#xff0c;真的有用吗&#xff1f; 一、引入话题 IT行业是一个快速发展和不断变化…

概率统计(二)

二维离散型 联合分布律 样本总数为16是因为&#xff0c;两封信分别可以放在4个信箱 边缘分布律 条件分布律 独立性 选填才能用秒杀 联合概率乘积不等于边缘概率的乘积则不独立 二维连续型 区间用一重积分面积用二重积分 离散型随机变量

Python题解Leetcode Hot100之二叉树

1. 二叉树的中序遍历 题目描述 给定一个二叉树&#xff0c;返回它的中序遍历。解题思路 使用递归的方法对左子树进行中序遍历&#xff0c;然后访问根节点&#xff0c;最后对右子树进行中序遍历。也可以使用栈来模拟递归的过程&#xff0c;迭代地进行中序遍历。代码class Solut…

医院挂号系统小程序的设计

管理员账户功能包括&#xff1a;系统首页&#xff0c;个人中心&#xff0c;患者管理&#xff0c;医生管理&#xff0c;专家信息管理&#xff0c;科室管理&#xff0c;预约信息管理&#xff0c;系统管理 微信端账号功能包括&#xff1a;系统首页&#xff0c;专家信息&#xff0…

Java入门-异常机制

java异常机制 异常概念 在Java中&#xff0c;异常处理(exception handling) : java语言或者程序员开发提供的一种机制&#xff0c;当有不正常的情况发生时&#xff0c;可以发出信号。这种发出信号的过程被称为抛出异常(throwing an exception)。 java异常体系 Error Error类对…

数据库SQL Server常用字符串函数

文章目录 字符串函数 字符串函数 CONCAT:拼接字符串 CONCAT(COLUMN1,_,COLUMN2) AS COLCONVERT&#xff1a;转换数据类型 CONVERT(data_type(length),data_to_be_converted,style)例如&#xff1a;CONVERT(VARCHAR(10),GETDATE(),110) SUBSTRING()&#xff1a;从字符串中返回…

24.6.30

星期一&#xff1a; 补cf global round26 D cf传送门 思路&#xff1a;把s中非a字符存下来&#xff0c;共m个&#xff0c;然后暴力检测&#xff0c;复杂度有点迷 代码如下&#xff1a; ll n;void solve(){string s; cin &…

硬件开发笔记(二十四):贴片电容的类别、封装介绍,AD21导入贴片电容、原理图和封装库3D模型

若该文为原创文章&#xff0c;转载请注明原文出处 本文章博客地址&#xff1a;https://hpzwl.blog.csdn.net/article/details/140241817 长沙红胖子Qt&#xff08;长沙创微智科&#xff09;博文大全&#xff1a;开发技术集合&#xff08;包含Qt实用技术、树莓派、三维、OpenCV…

(南京观海微电子)——电阻应用及选取

什么是电阻&#xff1f; 电阻是描述导体导电性能的物理量&#xff0c;用R表示。 电阻由导体两端的电压U与通过导体的电流I的比值来定义&#xff0c;即&#xff1a; 所以&#xff0c;当导体两端的电压一定时&#xff0c;电阻愈大&#xff0c;通过的电流就愈小&#xff1b;反之&…

Java+MySQL8.0.36+ElementUI数字化产科信息管理系统之”五色管理”

JavaMySQL8.0.36ElementUI数字化产科信息管理系统之”五色管理” 一、数字化产科信息管理系统概述 数字化产科信息管理五色管理是一种基于孕产妇妊娠风险的分类管理方法&#xff0c;通过数字化手段实现孕产妇全周期的健康风险评估与管理。该方法将孕产妇按照风险等级分为绿色、…

【HTML入门】第三课 - 标题、段落、空格

这一小节&#xff0c;我们说一些比较零散的知识&#xff0c;HTML课程中呢&#xff0c;其实就是一些标签&#xff0c;正是这些标签组成了前端网页的各种元素&#xff0c;所以你也可以叫他们标签元素。 像前两节我们说的&#xff0c;html head body title meta style 。这些都是…

3.js - 裁剪场景(多个scence)

不给newScence添加background、environment时 给newScence添加background、environment时 源码 // ts-nocheck// 引入three.js import * as THREE from three// 导入轨道控制器 import { OrbitControls } from three/examples/jsm/controls/OrbitControls// 导入lil.gui impor…

阶段三:项目开发---大数据开发运行环境搭建:任务5:安装配置Kafka

任务描述 知识点&#xff1a;安装配置Kafka 重 点&#xff1a; 安装配置Kafka 难 点&#xff1a;无 内 容&#xff1a; Kafka是由Apache软件基金会开发的一个开源流处理平台&#xff0c;由Scala和Java编写。Kafka是一种高吞吐量的分布式发布订阅消息系统&#xff0c;…