UniRest是什么?

UniRest是什么?

Unirest 是一套跨语言轻量级HTTP开发库,由Kong团队维护,此团队同时维护着另一个著名开源网关项目API Gateway Kong.

MAVEN安装

<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>3.5.00</version>
</dependency>

<!-- 需要作为独立jar文件引用时(包含隐式依赖) -->
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>3.5.00</version>
    <classifier>standalone</classifier>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

请求

使用JAVA语言,创建一个Unirest请求相当方便,一个常见的POST请求如下:

HttpResponse<JsonNode> response =Unirest.post("http://httpbin.org/post")
      .header("accept", "application/json")
      .queryString("apiKey", "123")
      .field("parameter", "value")
      .field("foo", "bar")
      .asJson();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

路由参数

如果需要在URL中加入动态路由参数,可以先在URL中通过一个占位符标记参数位置,之后通过routeParam方法,动态指定参数值,如下所示:

Unirest.get("http://httpbin.org/{fruit}")
     .routeParam("fruit", "apple")
     .asString();
  • 1
  • 2
  • 3

占位符的格式为{自定义名称},在示例中,{占位符}会被替换为 apple,并且所有占位符会自动使用
URL-Encoded转义。

查询参数

请求路径附带的参数可以通过如下方式逐个添加:

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

// 请求路径 "http://httpbin.org?fruit=apple&droid=R2D2"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

queryString 方法也支持通过数组,或Map传递参数

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

 // 请求路径 "http://httpbin.org?fruit=apple&fruit=orange&droid=R2D2&beatle=Ringo"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

请求头

请求头通过header方法,添加:

Unirest.get("http://httpbin.org")
            .header("Accept", "application/json")
            .header("x-custom-header", "hello")
            .asString();
  • 1
  • 2
  • 3
  • 4

Basic Authentication 认证

Unirest提供了一个方便的方法实现 Basic Authentication 认证,Unirest 会自动处理Base64编码部分,此认证建议使用HTTPS。

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

// 请求头 "Authorization: Basic dXNlcjpwYXNzd29yZDEh"
  • 1
  • 2
  • 3
  • 4
  • 5

请求体

请求体通过body方法指定,除非特别指定,否则请求头中 Content-Type 统一设置为:text/plain; charset=UTF-8

Unirest.post("http://httpbin.org")
                .body("This is the entire body")
                .asEmpty();
  • 1
  • 2
  • 3

body方法传入对象,支持用Jackson序列化对象方式生成请求体。

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

// This will use Jackson to serialize the object into JSON.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

JSON Patch支持

Unirest 原生支持JSON Patch 技术(参见 RFC-6902 http://jsonpatch.com/) 。json-patch请求默认的Content-Type是application/json-patch+json。

Unirest.jsonPatch("http://httpbin.org")
            .add("/fruits/-", "Apple")
            .remove("/bugs")
            .replace("/lastname", "Flintstone")
            .test("/firstname", "Fred")
            .move("/old/location", "/new/location")
            .copy("/original/location", "/new/location")
            .asJson();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

基本表单

通过body传输的表单name和value参数可以通过field指定,此类请求的Content-Type默认为application/x-www-form-urlencoded

Unirest.post("http://httpbin.org")
       .field("fruit", "apple")
       .field("droid", "R2D2")
       .asEmpty();
  • 1
  • 2
  • 3
  • 4

文件上传

可以通过POST表单提交二进制数据,例如:文件。这种类型的请求中,Content-Type默认为multipart/form-data。

Unirest.post("http://httpbin.org")
       .field("upload", new File("/MyFile.zip"))
       .asEmpty();
  • 1
  • 2
  • 3

对于大文件上传,可以通过InputStream方式上传,同时可以附加文件名。示例中使用FileInputStream举例,实际上也同时支持各类InputStream。

InputStream file = new FileInputStream(new File("/MyFile.zip"));

Unirest.post("http://httpbin.org")
       .field("upload", file, "MyFile.zip")
       .asEmpty();
  • 1
  • 2
  • 3
  • 4
  • 5

在上传大文件时,如果需要向用户展示进度条,可以通过提供一个ProgresMonitor来实现:

Unirest.post("http://httpbin.org")
                .field("upload", new File("/MyFile.zip"))
                .uploadMonitor((field, fileName, bytesWritten, totalBytes) -> {
                    updateProgressBarWithBytesLeft(totalBytes - bytesWritten);
                })
                .asEmpty();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

异步请求

所有请求都支持异步版本,示例如下:

CompletableFuture<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .field("param1", "value1")
  .field("param2", "value2")
  .asJsonAsync(response -> {
        int code = response.getStatus();
        JsonNode body = response.getBody();
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

请求分页

有些服务提供分页数据,Unirest可以通过一种标准方式,自动拉去全部数据。
使用这个功能需要提供两个方法参数。 第一个方法将返回内容转换为需要的HttpResponse对象, 另一个方法从返回内容中获取下一页的URL链接地址。此功能返回PagedList<HttpResponse>对象。 PagedList对象封装了处理返回结果的一些常用方法。
以下示例中,Unirest自动分页拉取了Doggos对象列表,下一页连接通过hearder内容获取。

PagedList<Doggos> result =  Unirest.get("https://somewhere/dogs")
                .asPaged(
                        r -> r.asObject(Doggos.class),
                        r -> r.getHeaders().getFirst("nextPage")
                );
  • 1
  • 2
  • 3
  • 4
  • 5

客户端证书

在需要客户端证书的情况下,unirest支持通过传递自定义的KeyStore对象,或提供一个有效的PKCS#12 keystore文件实现服务认证。

Unirest.config()
  .clientCertificateStore("/path/mykeystore.p12", "password1!");

Unirest.get("https://some.custom.secured.place.com")
                .asString();
  • 1
  • 2
  • 3
  • 4
  • 5

代理

Unirest支持通过proxy方法配置代理。需要注意的是,unirest不支持为单个请求,配置带有权限验证的代理,除非权限验证内容构建在URL中。

// 配置带有权限验证的代理
Unirest.config().proxy("proxy.com", 7777, "username", "password1!");

// 或使用无权限验证的代理
Unirest.config().proxy("proxy.com", 7777);

// 通过请求指定代理,这样会覆盖默认代理
// 这种情况下,只有不需要验证的代理可以生效
Unirest.get(MockServer.GET)
                .proxy("proxy.com", 7777)
                .asString();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

返回值

Unirest 在调用as[type]方法时,实际发送请求。这类方法同时限定了返回值类型。例如:Empty, String, File, Object, byte and Json.
返回值对象HttpResponse 封装了例如:status,headers等。返回值body内容,通过getBody() 获取。

返回空值

如果不需要处理返回body内容,asEmpty是一个十分好用的方法,返回内容仍然包含status 和headers。

HttpResponse response = Unirest.delete("http://httpbin.org").asEmpty()
  • 1

返回字符串

另一个方便的方法是通过asString方法获取返回字符串。

String body = Unirest.get("http://httpbin.org")
                     .asString()
                     .getBody();
  • 1
  • 2
  • 3

返回对象处理

通常使用RESTful 服务时,会对返回值进行json对象转换。在这种情况下,需要为Unirest指定ObjectMapper (参见ObjectMapper )。

Unirest 默认通过Google GSON来处理JSON数据。如果不希望使用默认处理方式,在使用asObject(Class)方法前,需要向Unirest提供ObjectMapper 接口的自定义实现。在初次指定之后,ObjectMapper 对象会被全局共享。

Unirest 同时提供一些ObjectMapper 插件, 例如:Jackson 、Gson. 可以通过maven center了解详情。

// 返回对象
Book book = Unirest.get("http://httpbin.org/books/1")
                   .asObject(Book.class)
                   .getBody();

// 通过GenericType支持构建泛型对象
List<Book> books = Unirest.get("http://httpbin.org/books/")
              .asObject(new GenericType<List<Book>>(){})
              .getBody();

Author author = Unirest.get("http://httpbin.org/books/{id}/author")
                       .routeParam("id", bookObject.getId())
                       .asObject(Author.class)
                       .getBody();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

对象返回值异常处理

在JSON转化为对象过程中出现异常时,body返回值为null,需要通过getParsingError获取异常信息和返回的body值。

UnirestParsingException ex = response.getParsingError().get();

ex.getOriginalBody(); // 返回body原始值
ex.getMessage(); // 处理过程出现的异常信息
ex.getCause(); // 原始parsing exception
  • 1
  • 2
  • 3
  • 4
  • 5

错误信息对象映射

有些场景下,REST API’s 会返回错误信息对象,通过以下方式可以进行转换:

HttpResponse<Book> book = Unirest.get("http://httpbin.org/books/{id}")
                                     .asObject(Book.class);

    // 在没有错误的情况下,此方法返回null
    Error er = book.mapError(Error.class);

    // ifFailure 方法中也可以做类似自动转换
    Unirest.get("http://httpbin.org/books/{id}")
           .asObject(Book.class)
           .ifFailure(Error.class, r -> {
                    Error e = r.getBody();
           });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

返回值类型转换

如果不想实现ObjectMapper ,也可以通过如下方法自动转换返回内容。

int body = Unirest.get("http://httpbin/count")
                      .asString()
                      .mapBody(Integer::valueOf);
  • 1
  • 2
  • 3

返回文件

Unirest 支持简单下载文件,或从响应体中转换文件下载,只需提供下载路径即可:

File result = Unirest.get("http://some.file.location/file.zip")
                .asFile("/disk/location/file.zip")
                .getBody();
  • 1
  • 2
  • 3

返回JSON

在不需要Object Mapper时,Unirest 还提供一个轻量级JSON对象响应体。

String result = Unirest.get("http://some.json.com")
                       .asJson()
                       .getBody()
                       .getObject()
                       .getJSONObject("thing")
                       .getJSONArray("foo")
                       .get(0)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

返回大量数据

通过一些方法 (asString, asJson) Unirest会将整个返回值加载到内存。 以下方法可以获取数据流对象,支持处理大量数据的情况:

Map r = Unirest.get(MockServer.GET)
                .queryString("foo", "bar")
                .asObject(i -> new Gson().fromJson(i.getContentReader(), HashMap.class))
                .getBody();
  • 1
  • 2
  • 3
  • 4

消费者模式

Unirest.get(MockServer.GET)
                .thenConsumeAsync(r -> {
                       // 此处可以写数据到文件
                });
  • 1
  • 2
  • 3
  • 4

Error Handling

HttpResponse支持链式处理成功和失败请求。
在返回值为2XX同时对象转换成功时,ifSuccess(Consumer<HttpResponse> response) 方法会被调用。在返回值为400+时或者对象转换失败时,ifFailure(Consumer会被调用。

Unirest.get("http://somewhere")
                .asJson()
                .ifSuccess(response -> someSuccessMethod(response))
                .ifFailure(response -> {
                    log.error("Oh No! Status" + response.getStatus());
                    response.getParsingError().ifPresent(e -> {
                        log.error("Parsing Exception: ", e);
                        log.error("Original body: " + e.getOriginalBody());
                    });
                });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Configuration

通过Unirest.config(),可以配置http请求的常见参数。参数详见官方文档(http://kong.github.io/unirest-java/#configuration)

Unirest.config()
           .socketTimeout(500)
           .connectTimeout(1000)
           .concurrency(10, 5)
           .proxy(new Proxy("https://proxy"))
           .setDefaultHeader("Accept", "application/json")
           .followRedirects(false)
           .enableCookieManagement(false)
           .addInterceptor(new MyCustomInterceptor());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

全局拦截器

Unirest支持通过配置全局拦截器,实现统一日志,注入参数等操作。
示例:
Interceptor.java

自定义Apache Clients

Unirest 目前通过Apache Http Client提供底层 实现, 未来可能发生变化。
Unirest支持设置自定义Apache HttpClient 和HttpAsyncClient.

Unirest.config()
            .httpClient(ApacheClient.builder(myClient))
            .asyncClient(ApacheAsyncClient.builder(myAsyncClient));Copy

Unirest的请求配置也可以覆盖
Unirest.config()
            .httpClient(ApacheClient.builder(client)
                .withRequestConfig((c,r) -> RequestConfig.custom().build()
                );
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

配置不同客户端

通常,Unirest维护一个主单例对象。但有些情况下,例如:需要为不同系统设定不同配置,或需要为测试目的避开静态上下文时,可以使用如下方式:

 //第一个Unirest对象
    UnirestInstance unirest = Unirest.primaryInstance();
    unirest.config().connectTimeout(5000);
    String result = unirest.get("http://foo").asString().getBody();

    //第二个Unirest对象
    UnirestInstance unirest = Unirest.spawnInstance();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Object Mappers

Unirest 提供一些基于著名JSON库的ObjectMapper (Jackson and GSON)。可以通过以下方式引用。

<!-- https://mvnrepository.com/artifact/com.konghq/unirest-objectmapper-jackson -->
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-objectmapper-jackson</artifactId>
    <version>3.5.00</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.konghq/unirest-object-mappers-gson -->
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-object-mappers-gson</artifactId>
    <version>3.5.00</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

Metrics

Unirest 支持动态收集指标的钩子函数。 此轻量级框架支持两类事件:
1、请求发生前
2、请求发生后
上下文信息例如方法名和请求路径等在这两个事件中都已经提供,因此基本上可以借助此框架收集到需要的任何指标信息。一个简单示例如下:

Unirest.config().instrumentWith(requestSummary -> {
              long startNanos = System.nanoTime();
              return (responseSummary,exception) -> logger.info("path: {} status: {} time: {}",
                      requestSummary.getRawPath(),
                      responseSummary.getStatus(),
                      System.nanoTime() - startNanos);
   });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

关闭连接

Unirest 启动了一个后台事件总线 ,需要调用以下方法才能关闭

Unirest.shutdown();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值