超級好用的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.pswp.cn/web/40728.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/40728.shtml
英文地址,請注明出處:http://en.pswp.cn/web/40728.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ePTFE膜(膨體聚四氟乙烯膜)應用前景廣闊 本土企業技術水平不斷提升

ePTFE膜&#xff08;膨體聚四氟乙烯膜&#xff09;應用前景廣闊 本土企業技術水平不斷提升 ePTFE膜全稱為膨體聚四氟乙烯膜&#xff0c;指以膨體聚四氟乙烯&#xff08;ePTFE&#xff09;為原材料制成的薄膜。ePTFE膜具有耐化學腐蝕、防水透氣性好、耐候性佳、耐磨、抗撕裂等優…

自然語言處理(NLP)—— 期末復習總

1. 結構主義方法The structural Approach 1.1 語素學Graphemics/音素學phonemics 音素phonemes、書面符號written signs、字符character。這一部分關注語言的最小聲音單位&#xff08;音素phonemes&#xff09;以及這些聲音如何通過書面符號written signs或字符character來表示…

如何做到高級Kotlin強化實戰?(二)

高級Kotlin強化實戰&#xff08;二&#xff09; 2.Kotlin 與 Java 比較 2.Kotlin 與 Java 比較 2.5 字符串拼接 //Java String firstName "Android"; String lastName "enginner"; String message "My name is: " firstName " "…

Web美食分享平臺的系統-計算機畢業設計源碼45429

基于Web美食分享平臺的系統設計與實現 摘 要 本研究基于Spring Boot框架&#xff0c;設計并實現了一個Web美食分享平臺&#xff0c;旨在為用戶提供一個交流分享美食體驗的社區平臺。該平臺涵蓋了用戶注冊登錄、美食制作方法分享發布、點贊評論互動等功能模塊&#xff0c;致力于…

3D Web輕量化平臺HOOPS Web Platform的功能與應用分析

隨著3D技術在多個行業的廣泛應用&#xff0c;對于3D模型輕量化的需求日益增長。HOOPS Web Platform作為一個先進的3D模型輕量化平臺&#xff0c;為開發人員提供了一整套工具來構建和部署基于Web的工程應用程序。本文將分析HOOPS Web Platform的核心功能和它在不同領域的應用情況…

軟件工程學面向對象

一、面向對象方法學概述 傳統的生命周期方法學在消除軟件非結構化、促進軟件開發工程化方面起了積極的作用&#xff0c;但仍有許多不足&#xff0c;存在的主要問題有&#xff1a;①生產率提高的幅度不能滿足需要&#xff1b; ②軟件重用程度很低&#xff1b; ③軟件很難維護&a…

MySQL中的MVCC解析

MySQL中的MVCC解析 多版本并發控制是MySQL中實現高并發的一種關鍵技術。通過對數據進行多版本的管理&#xff0c;MVCC能夠在保證數據一致性的同時&#xff0c;提高數據庫的并發性能。本文將深入探討MySQL中的MVCC機制&#xff0c;包括其原理、實現方式以及優勢。 MVCC的原理 …

華為機試HJ22汽水瓶

華為機試HJ22汽水瓶 題目&#xff1a; 某商店規定&#xff1a;三個空汽水瓶可以換一瓶汽水&#xff0c;允許向老板借空汽水瓶&#xff08;但是必須要歸還&#xff09;。 小張手上有n個空汽水瓶&#xff0c;她想知道自己最多可以喝到多少瓶汽水。 想法&#xff1a; 因為可以…

硬件開發工具Arduino IDE

招聘信息共享社群 關聯上篇文章樂鑫ESPRESSIF芯片開發簡介 Arduino IDE&#xff08;集成開發環境&#xff09;是為Arduino硬件開發而設計的一款軟件&#xff0c;它提供了一個易于使用的圖形界面&#xff0c;允許用戶編寫、編輯、編譯和上傳代碼到Arduino開發板。Arduino IDE的…

深入分析 Android BroadcastReceiver (八)

文章目錄 深入分析 Android BroadcastReceiver (八)1. 系統與自定義實現1.1 系統廣播機制1.1.1 系統廣播的實現原理1.1.2 系統廣播的源碼分析 1.2 自定義廣播機制1.2.1 自定義廣播的實現步驟1.2.2 自定義廣播的源碼分析 2. 廣播機制設計的初衷與優勢2.1 設計初衷2.2 優勢 3. 總…

有了提示詞框架的雞,你就能讓AI下提示詞的蛋~

我們在問AI問題的時候&#xff0c;是不是經常感覺AI的回答沒有別人的那么好&#xff1f; 難道別人的AI更加聰明&#xff1f; 很可能是因為我們的提示詞沒寫好&#xff0c;那么&#xff0c;寫出好的提示詞很難嗎&#xff1f; 一點都不難&#xff0c;其實這都是有套路的&#…

Hive排序字段解析

Hive排序字段解析 在Hive中&#xff0c;CLUSTER BY、DISTRIBUTE BY、SORT BY和ORDER BY是用于數據分發和排序的關鍵子句&#xff0c;它們各自有不同的用途和性能特點。讓我們逐一解析這些子句&#xff1a; 1. DISTRIBUTE BY 用途: 主要用于控制如何將數據分發到Reducer。它可…

NSSCTF-Web題目24(RCE-空格繞過、過濾繞過)

目錄 [MoeCTF 2021]babyRCE 1、題目 2、知識點 3、思路 [SWPUCTF 2022 新生賽]funny_web 4、題目 5、知識點 6、思路 [MoeCTF 2021]babyRCE 1、題目 2、知識點 空格繞過、過濾繞過 3、思路 出現源碼&#xff0c;進行代碼審計 需要我們GET方式上傳一個rce變量&#x…

解碼注意力機制:自注意力與跨注意力的奧秘

標題&#xff1a;解碼注意力機制&#xff1a;自注意力與跨注意力的奧秘 自注意力&#xff08;Self-Attention&#xff09;和跨注意力&#xff08;Cross-Attention&#xff09;是深度學習中的重要概念&#xff0c;尤其在自然語言處理&#xff08;NLP&#xff09;領域的Transfor…

[FreeRTOS 功能應用] 互斥量 功能應用

文章目錄 一、基礎知識點二、代碼講解三、結果演示四、代碼下載 一、基礎知識點 [FreeRTOS 基礎知識] 互斥量 概念 [FreeRTOS 內部實現] 互斥量 本實驗是基于STM32F103開發移植FreeRTOS實時操作系統&#xff0c;互斥量實戰操作。 使用工具&#xff1a;Keil、串口工具 二、代碼…

Rust變量綁定

變量綁定 Rust 通過靜態類型確保類型安全。變量綁定可以在聲明時說明類型&#xff0c;不過在多數情況下&#xff0c;編譯器能夠從上下文推導出變量的類型&#xff0c;從而大大減少了類型說明的工作。 使用 let 綁定操作可以將值&#xff08;比如字面量&#xff09;綁定&#…

全面解析智慧校園行政辦公的協作日程功能

在智慧校園的行政辦公生態系統中&#xff0c;協作日程功能成為促進團隊互動與工作同步的橋梁&#xff0c;它超越了傳統個人日程的范疇&#xff0c;強調的是集體效率與信息的無縫對接。這一功能設計的核心&#xff0c;在于創造一個開放而有序的平臺&#xff0c;讓教育工作者們能…

2-4 Softmax 回歸的從零開始實現

就像我們從零開始實現線性回歸一樣&#xff0c; 我們認為softmax回歸也是重要的基礎&#xff0c;因此應該知道實現softmax回歸的細節。 本節我們將使用剛剛在2-3節中引入的Fashion-MNIST數據集&#xff0c; 并設置數據迭代器的批量大小為256。 import torch from IPython impo…

【chtagpt】pytorch中的方法對象和屬性

文章目錄 定義一個簡單的類屬性和方法對象的區別PyTorch 張量中的屬性和方法對象進一步解釋總結self.value value 的解釋示例解釋總結 為了更好地理解方法對象和屬性&#xff0c;我們可以通過一個簡單的類來演示這兩者的區別及其用法。 定義一個簡單的類 我們定義一個名為 My…

開發個人Go-ChatGPT--1 項目介紹

開發個人Go-ChatGPT--1 項目介紹 開發個人Go-ChatGPT--1 項目介紹知識點大綱文章目錄項目地址 開發個人Go-ChatGPT–1 項目介紹 本文將以一個使用Ollama部署的ChatGPT為背景&#xff0c;主要還是介紹和學習使用 go-zero 框架&#xff0c;開發個人Go-ChatGPT的服務器后端&#…