【Java技术指南】「Unirest编程专题」一起认识一下一个“灰常”优秀的Http工具,让Http开发变得如此简单

300 阅读7分钟

Unirest-Java是一个轻量级的HTTP客户端库,它提供了简单易用的API,可以帮助Java开发人员快速地发送HTTP请求和处理响应。在本文中,我们将深入探讨Unirest-Java的技术细节和使用方法。

Unirest-Java的优点

  1. 简单易用:Unirest-Java提供了一组简单易用的API,可以帮助Java开发人员快速地发送HTTP请求和处理响应。

  2. 轻量级:Unirest-Java是一个轻量级的HTTP客户端库,它不需要任何外部依赖项,可以很容易地集成到Java应用程序中。

  3. 支持多种HTTP方法:Unirest-Java支持GET、POST、PUT和DELETE等多种HTTP方法,可以满足不同的需求。

  4. 支持异步请求:Unirest-Java支持异步请求,可以在发送请求时指定回调函数,当请求完成时自动调用回调函数。

Unirest-Java的安装和配置

Unirest-Java可以通过Maven或Gradle进行安装和配置。在Maven中,只需要在pom.xml文件中添加以下依赖项:

<!-- Pull in as a traditional dependency -->
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>3.14.1</version>
</dependency>

<!-- OR as a snazzy new standalone jar with shaded dependencies -->
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>3.14.1</version>
    <classifier>standalone</classifier>
</dependency>

Unirest-Java的使用方法

Unirest-Java提供了一组简单易用的API,可以帮助Java开发人员快速地发送HTTP请求和处理响应。

请求处理操作

所以你可能想知道使用 Unirest 如何使在 Java 中创建请求更容易,这里有一个基本的 POST 请求,它将解释一切:

HttpResponse<JsonNode> response = Unirest.post("http://localhost/post")
      .header("accept", "application/json")
      .queryString("apiKey", "123")
      .field("parameter", "value")
      .field("firstname", "Gary")
      .asJson();

调用asType时会发出请求,类型包括Json、字符串、对象空和文件

路由参数(Route Parameters)

有时您想在URL中添加动态参数,您可以通过在 URL 中添加占位符,然后使用 routeParam 函数设置路由参数来轻松完成,例如:

Unirest.get("http://localhost/{fruit}")
     .routeParam("fruit", "apple")
     .asString();

请求的结果是http://localhost/apple

  • 占位符 {水果} 将替换为apple。
  • 占位符的格式就像用大括号换行一样简单:{custom_name}
  • 所有参数值都将为您进行URL编码

默认基本的URL(Default Base URLs)

您可以配置默认基础URL,以用于不包含完整URL的所有请求,此配置将导致 GET 到“homestar.com/runner”。

Unirest.config().defaultBaseUrl("http://homestar.com");
   Unirest.get("/runner").asString();

查询参数(Query Parameters)

可以逐个构建查询字符串参数

Unirest.get("http://localhost")
                .queryString("fruit", "apple")
                .queryString("droid", "R2D2")
                .asString();

使用 "http://localhost?fruit=apple&droid=R2D2"进行请求Http操作。


同样,所有参数值都将进行URL编码,您还可以将查询字符串作为数组和映射传入:

Unirest.get("http://localhost")
        .queryString("fruit", Arrays.asList("apple", "orange"))
        .queryString(ImmutableMap.of("droid", "R2D2", "beatle", "Ringo"))
        .asString();

请求的内容为 "http://localhost?fruit=apple&fruit=orange&droid=R2D2&beatle=Ringo"

请求头(Headers)

可以使用标头方法添加请求标头。

Unirest.get("http://localhost")
            .header("Accept", "application/json")
            .header("x-custom-header", "hello")
            .asString();

基本身份验证(Basic Authentication)

Unirest 公开了一个快捷方式,用于在需要时执行基本身份验证。Unirest 处理 Base64 编码部分。请确保您始终通过HTTPS执行此操作!

Unirest.get("http://localhost")
            .basicAuth("user", "password1!")
            .asString();

添加了请求头 “Authorization: Basic dXNlcjpwYXNzd29yZDEh”

请求体(Body Data)

实体主体

您可以轻松地发送请求头。这是大多数REST服务的默认行为。除非另行指定,否则默认内容类型为Content-Type 是 text/plain; charset=UTF-8。

Unirest.post("http://localhost")
                .body("This is the entire body")
                .asEmpty();

还可以发布为使用配置的对象映射器序列化的对象。Unirest带有一个默认映射器,它将使用流行的Google Gson库序列化为json。

Unirest.post("http://localhost")
            .header("Content-Type", "application/json")
            .body(new SomeUserObject("Bob"))
            .asEmpty();

这将使用Jackson将对象序列化为JSON。

发送GET请求

HttpResponse<String> response = Unirest.get("http://httpbin.org/get")
  .header("accept", "application/json")
  .queryString("apiKey", "123")
  .asString();

发送POST请求

HttpResponse<String> response = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .field("param1", "value1")
  .field("param2", "value2")
  .asString();

发送PUT请求

HttpResponse<String> response = Unirest.put("http://httpbin.org/put")
  .header("accept", "application/json")
  .field("param1", "value1")
  .field("param2", "value2")
  .asString();

发送DELETE请求

HttpResponse<String> response = Unirest.delete("http://httpbin.org/delete")
  .header("accept", "application/json")
  .queryString("apiKey", "123")
  .asString();

处理响应

HttpResponse<String> response = Unirest.get("http://httpbin.org/get")
  .header("accept", "application/json")
  .queryString("apiKey", "123")
  .asString();

int status = response.getStatus();
String body = response.getBody();
Headers headers = response.getHeaders();

基本表单

基本的http名称值主体参数可以通过简单的字段调用来传递。这种类型请求的Content-Type默认为application/x-www-form-urlencoded。

Unirest.post("http://localhost")
       .field("fruit", "apple")
       .field("droid", "R2D2")
       .asEmpty();

这将发布一个与HTML表单相同的简单名称-值对主体。如:“fruit=apple&droid=R2D2”。


文件上传

你也可以采用表单的形式发布二进制数据。就像文件一样。此类型请求的内容类型默认为multipart/form-data。

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) -> {
                    // 实现你的输出即可。
                })
           .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在您调用它的as〔type〕方法时发出实际请求。这些方法还通知Unirest将响应映射到什么类型。选项有Empty、String、File、Object、byte和Json。

响应返回为HttpResponse,其中HttpResponse对象具有所有常见的响应数据,如状态和标头。可以使用.getBody()方法通过所需类型访问Body(如果存在)。

Empty响应体

如果你不需要得到结果返回,asEmpty是最简单的选择。但是仍然会得到其他的响应信息。

HttpResponse response = Unirest.delete("http://localhost").asEmpty()

String响应体

最简单的响应类型是字符串。在那之后,你可以用它做任何你想做的事。

String body = Unirest.get("http://localhost")
					 .asString()
					 .getBody();

JSON响应体

当您不需要完整的Object Mapper时,Unirest提供了一种轻量级的JSON响应类型。

String result = Unirest.get("http://some.json.com")
				       .asJson()
				       .getBody()
				       .getObject()
				       .getJSONObject("car")
				       .getJSONArray("wheels")
				       .get(0)

大数据响应体

一些响应方法(asString、asJson)将整个响应流读取到内存中。为了读取原始流并处理大量响应,您可以使用以下几种功能方法:

Map r = Unirest.get(MockServer.GET)
                .queryString("firstname", "Gary")
                .asObject(i -> new Gson().fromJson(i.getContentReader(), HashMap.class))
                .getBody();
消费者模式
Unirest.get(MockServer.GET)
                .thenConsumeAsync(r -> {
                       // something like writing a file to disk
                });

Object Mapped响应体

  • 大多数时候,在使用RESTful服务时,您可能希望将响应映射到对象中。为此,您需要为Unirest配置提供ObjectMapper的实现。如果响应是JSON,那么你很幸运,Unirest附带了一个基于Google GSON的基本JsonObjectMapper。

  • 在创建asObject(类)之前,有必要提供ObjectMapper接口的自定义实现(如果您不希望使用默认映射器)。这应该只在第一次执行,因为ObjectMapper的实例将被全局共享。

Unirest提供了一些插件来实现流行的对象映射器,如Jackson和Gson。

例如

响应体的对象
Book book = Unirest.get("http://localhost/books/1")
                   .asObject(Book.class)
                   .getBody();
响应体的对象

可以通过使用GenericType子类来解析泛型类型,以避免擦除。

List<Book> books = Unirest.get("http://localhost/books/")
			  .asObject(new GenericType<List<Book>>(){})
			  .getBody();

直接采用反射进行获取对象

Author author = Unirest.get("http://localhost/books/{id}/author")
                       .routeParam("id", bookObject.getId())
                       .asObject(Author.class)
                       .getBody();

总结

Unirest-Java是一个简单易用、轻量级的HTTP客户端库,它提供了多种HTTP方法和异步请求支持,可以帮助Java开发人员快速地发送HTTP请求和处理响应。如果你正在寻找一个简单易用的HTTP客户端库,那么Unirest-Java是一个不错的选择。