当前位置: 首页 > 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();}
}
http://www.lryc.cn/news/393214.html

相关文章:

  • 在原有的iconfont.css文件中加入新的字体图标
  • 使用 ESP32-WROOM + DHT11 做个无屏温湿度计
  • 如何使用 SwiftUI 构建 visionOS 应用
  • InspireFace-商用级的跨平台开源人脸分析SDK
  • 华为HCIP Datacom H12-821 卷24
  • TikTok马来西亚直播网络怎么配置?
  • 基于若依的文件上传、下载
  • 论文回顾 | CVPR 2021 | How to Calibrate Your Event Camera | 基于图像重建的事件相机校准新方法
  • 高级java每日一道面试题-2024年7月1日
  • 当需要对多个表进行联合更新操作时,怎样确保数据的一致性?
  • 数据结构-线性表的应用
  • cpp http server/client
  • 昇思25天学习打卡营第2天|MindSpore快速入门
  • django之url路径
  • 【OnlyOffice】桌面应用编辑器,插件开发大赛,等你来挑战
  • [学习笔记]SQL学习笔记(连载中。。。)
  • Buuctf之SimpleRev做法
  • 【云原生监控】Prometheus 普罗米修斯从搭建到使用详解
  • 【C++】模板进阶--保姆级解析(什么是非类型模板参数?什么是模板的特化?模板的特化如何应用?)
  • Cookie与Session
  • Nuxt3 的生命周期和钩子函数(十一)
  • Windows ipconfig命令详解,Windows查看IP地址信息
  • 在C#/Net中使用Mqtt
  • VBA提取word表格内容到excel
  • html+css+js图片手动轮播
  • 【十三】图解 Spring 核心数据结构:BeanDefinition 其二
  • 数据库作业
  • 12、matlab中for循环,if else判断语句,break和continue用法以及switch case语句使用
  • AcWing 3207:门禁系统 ← 桶排序中“桶”的思想
  • 开发个人Go-ChatGPT--3 服务拆分