一、簡介
Unirest-Java是一個輕量級的HTTP客戶端庫,用于在Java應用程序中發送HTTP請求。
它提供了簡單易用的API,可以方便地處理GET、POST、PUT、DELETE等HTTP方法。
Unirest-Java支持異步和同步請求,可以輕松地與JSON、XML等數據格式進行交互。此外,它還支持文件上傳和下載、Cookie管理等功能。
總之,Unirest-Java是一個功能強大且易于使用的HTTP客戶端庫,適用于各種Java應用程序。
官網:http://kong.github.io/unirest-java/
二、安裝
1、Java8
<dependency><groupId>com.konghq</groupId><artifactId>unirest-java</artifactId><version>3.14.1</version></dependency>
1、Java11以上
<dependencyManagement><dependencies><!-- https://mvnrepository.com/artifact/com.konghq/unirest-java-bom --><dependency><groupId>com.konghq</groupId><artifactId>unirest-java-bom</artifactId><version>4.0.12</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement><dependencies>
<!-- https://mvnrepository.com/artifact/com.konghq/unirest-java-core -->
<dependency><groupId>com.konghq</groupId><artifactId>unirest-java-core</artifactId>
</dependency><!-- pick a JSON module if you want to parse JSON include one of these: -->
<!-- Google GSON -->
<dependency><groupId>com.konghq</groupId><artifactId>unirest-object-mappers-gson</artifactId>
</dependency><!-- OR maybe you like Jackson better? -->
<dependency><groupId>com.konghq</groupId><artifactId>unirest-objectmapper-jackson</artifactId>
</dependency>
</dependencies>
三、GET請求
使用Unirest庫發送一個HTTP GET請求到"http://localhost/{fruit}“,其中”{fruit}“是一個路由參數,其值為"apple”。然后,它將響應轉換為字符串。
Unirest.get("http://localhost/{fruit}").routeParam("fruit", "apple").asString();
使用Unirest庫發送一個HTTP GET請求到"http://localhost",并添加了兩個查詢參數:“fruit"的值為"apple”,“droid"的值為"R2D2”。最后,將響應轉換為字符串。
Unirest.get("http://localhost").queryString("fruit", "apple").queryString("droid", "R2D2").asString();
使用Unirest庫發送一個HTTP GET請求到"http://localhost",并添加了兩個查詢參數:"fruit"的值為一個包含"apple"和"orange"的列表,另一個查詢參數是一個不可變的映射(ImmutableMap),其中包含了"droid"和"beatle"兩個鍵值對。最后,將響應轉換為字符串。
Unirest.get("http://localhost").queryString("fruit", Arrays.asList("apple", "orange")).queryString(ImmutableMap.of("droid", "R2D2", "beatle", "Ringo")).asString();
使用Unirest庫發送一個HTTP GET請求到"http://localhost",并設置了兩個請求頭:“Accept"設置為"application/json”,表示期望服務器返回JSON格式的數據;“x-custom-header"設置為"hello”,表示自定義了一個名為"x-custom-header"的請求頭。最后,將響應轉換為字符串。
Unirest.get("http://localhost").header("Accept", "application/json").header("x-custom-header", "hello").asString();
使用Unirest庫發送一個HTTP GET請求到"http://localhost",并設置了基本的認證信息。其中,"user"和"password1!"分別表示用戶名和密碼。
最后,將響應轉換為字符串。
Unirest.get("http://localhost").basicAuth("user", "password1!").asString();
使用Unirest庫發送一個HTTP GET請求到"https://somewhere/dogs",并將響應結果轉換為PagedList類型。
具體來說,代碼中的.asPaged()方法用于處理分頁數據。它接受兩個參數:
r -> r.asObject(Doggos.class):這是一個Lambda表達式,用于將響應結果轉換為Doggos類型的對象列表。其中,r表示響應結果,r.asObject(Doggos.class)表示將響應結果轉換為Doggos類型的對象。
r -> r.getHeaders().getFirst(“nextPage”):這也是一個Lambda表達式,用于獲取下一頁的鏈接。其中,r表示響應結果,r.getHeaders().getFirst(“nextPage”)表示從響應頭中獲取名為"nextPage"的第一個值,即下一頁的鏈接。
通過這兩個Lambda表達式,代碼可以自動處理分頁數據,并將每一頁的數據轉換為Doggos類型的對象列表。
最終,結果將被存儲在名為result的PagedList變量中。
PagedList<Doggos> result = Unirest.get("https://somewhere/dogs").asPaged(r -> r.asObject(Doggos.class),r -> r.getHeaders().getFirst("nextPage"));
使用Unirest庫發送一個HTTP GET請求到"https://some.custom.secured.place.com",并獲取響應結果的字符串表示。
首先,Unirest.config()用于配置Unirest客戶端的行為。在這個例子中,它設置了客戶端證書存儲路徑為"/path/mykeystore.p12",并指定了密碼為"password1!"。這意味著在發送請求時,客戶端將使用指定的證書進行身份驗證。
然后,Unirest.get(“https://some.custom.secured.place.com”)用于創建一個GET請求,目標URL為"https://some.custom.secured.place.com"。
最后,.asString()方法用于將響應結果轉換為字符串表示。這樣,你可以對返回的數據進行處理或分析。
Unirest.config().clientCertificateStore("/path/mykeystore.p12", "password1!");Unirest.get("https://some.custom.secured.place.com").asString();
代理
有時您需要通過代理進行隧道傳輸。Unirest 可以配置為執行此操作。請注意,除非您要將其構建到 URL 本身中,否則無法按請求配置經過身份驗證的代理。
// Configure with authentication:Unirest.config().proxy("proxy.com", 7777, "username", "password1!");// or withoutUnirest.config().proxy("proxy.com", 7777);// or pass it in the request. This will override any proxy done in the config// currently only unauthenticated proxies workUnirest.get(MockServer.GET).proxy("proxy.com", 7777).asString();
四、POST請求
使用Unirest庫發送一個HTTP POST請求到"http://localhost/post這段代碼是使用Unirest庫發送一個HTTP POST請求到"http://localhost/post",并獲取響應結果的JsonNode表示。
具體來說,代碼執行了以下操作:
使用Unirest.post()方法創建一個POST請求,目標URL為"http://localhost/post"。
通過.header(“accept”, “application/json”)設置請求頭中的"Accept"字段為"application/json",表示期望服務器返回JSON格式的數據。
通過.queryString(“apiKey”, “123”)添加查詢參數"apiKey",其值為"123"。
通過.field(“parameter”, “value”)和.field(“firstname”, “Gary”)分別添加兩個表單字段,分別為"parameter"和"firstname",它們的值分別為"value"和"Gary"。
最后,通過.asJson()方法將響應結果轉換為JsonNode類型,并將其賦值給變量response。
HttpResponse<JsonNode> response = Unirest.post("http://localhost/post").header("accept", "application/json").queryString("apiKey", "123").field("parameter", "value").field("firstname", "Gary").asJson();
使用Unirest庫發送一個HTTP POST請求到"http://localhost",并這段代碼是使用Unirest庫發送一個HTTP POST請求到"http://localhost",并設置請求體的內容為"This is the entire body"。最后通過.asEmpty()方法指定響應結果的處理方式為空處理。
具體來說,代碼執行了以下操作:
使用Unirest.post(“http://localhost”)創建一個POST請求,目標URL為"http://localhost"。
通過.body(“This is the entire body”)設置請求體的內容為"This is the entire body"。
最后通過.asEmpty()方法指定響應結果的處理方式為空處理。這意味著在接收到響應后,不會對響應內容進行任何處理或解析。
Unirest.post("http://localhost").body("This is the entire body").asEmpty();
使用Unirest庫發送一個HTTP POST請求到"http://localhost"。它設置了請求頭中的"Content-Type"為"application/json",表示請求體中的數據類型是JSON格式。然后,它將一個名為"Bob"的SomeUserObject對象作為請求體發送出去。最后,通過調用.asEmpty()方法指定響應結果的處理方式為空處理,即不對響應內容進行任何處理或解析。
Unirest.post("http://localhost").header("Content-Type", "application/json").body(new SomeUserObject("Bob")).asEmpty();
使用Unirest庫發送一個JSON Patch請求。具體來說,它執行了以下操作:
向"http://localhost"發送一個JSON Patch請求。
在"/fruits/-“路徑下添加一個名為"Apple"的元素。
從”/bugs"路徑下移除元素。
將"/lastname"路徑下的值替換為"Flintstone"。
測試"/firstname"路徑下的值是否等于"Fred"。
將"/old/location"路徑下的元素移動到"/new/location"路徑下。
將"/original/location"路徑下的元素復制到"/new/location"路徑下。
將結果以JSON格式返回。
Unirest.jsonPatch("http://localhost").add("/fruits/-", "Apple").remove("/bugs").replace("/lastname", "Flintstone").test("/firstname", "Fred").move("/old/location", "/new/location").copy("/original/location", "/new/location").asJson();
使用Unirest庫發送一個POST請求到"http://localhost"。它向該URL發送兩個字段,一個是"fruit",值為"apple",另一個是"droid",值為"R2D2"。最后,它調用asEmpty()方法來發送請求并返回一個空的響應。
Unirest.post("http://localhost").field("fruit", "apple").field("droid", "R2D2").asEmpty();
五、PUT請求
HttpResponse<JsonNode> response = Unirest.put(url).header("Content-Type", "application/json").body(json).asJson();
六、DELETE請求
try {HttpResponse<String> response = Unirest.delete(url).asString();System.out.println("Status code: " + response.getStatus());System.out.println("Response body: " + response.getBody());} catch (UnirestException e) {e.printStackTrace();}
七、文件上傳
Unirest.post("http://localhost").field("upload", new File("/MyFile.zip")).asEmpty();
對于大文件,您可能需要使用 InputStream。如果需要,請為其傳遞文件名。 我們在這里使用 FileInputStream,但它實際上可以是任何類型的 InputStream。
InputStream file = new FileInputStream(new File("/MyFile.zip"));Unirest.post("http://localhost").field("upload", file, "MyFile.zip").asEmpty();
上傳進度監控
如果要上傳大文件,則可能需要向用戶提供一些進度條時間。您可以通過提供 ProgresMonitor 來監視此進度。
Unirest.post("http://localhost").field("upload", new File("/MyFile.zip")).uploadMonitor((field, fileName, bytesWritten, totalBytes) -> {updateProgressBarWithBytesLeft(totalBytes - bytesWritten);}).asEmpty();
異步請求
有時,大多數時候,你希望你的應用程序是異步的而不是阻塞的,Unirest 在 Java 中使用匿名回調或直接方法放置來支持這一點。所有請求類型還支持異步版本。
CompletableFuture<HttpResponse<JsonNode>> future = Unirest.post("http://localhost/post").header("accept", "application/json").field("param1", "value1").field("param2", "value2").asJsonAsync(response -> {int code = response.getStatus();JsonNode body = response.getBody();});
八、文件下載
有時,您只想下載文件,或者將響應正文捕獲到文件中。Unirest 可以兩者兼而有之。只需告訴 Unirest 您要將文件放在哪里即可。
File result = Unirest.get("http://some.file.location/file.zip").asFile("/disk/location/file.zip").getBody();
下載進度監控
如果要上傳大文件,則可能需要向用戶提供一些進度條時間。您可以通過提供 ProgresMonitor 來監視此進度。
Unirest.get("http://localhost").downLoadMonitor((b, fileName, bytesWritten, totalBytes) -> {updateProgressBarWithBytesLeft(totalBytes - bytesWritten);}).asFile("/disk/location/file.zip");