Unirest一款轻量级的HTTP客户端库

在java工程里如果需要透传什么信息给一个http接口的话,我们往往会使用HttpClient这个类,然后set很多param参数,这个类自然是很优秀的也被很多线上工程使用着,但是使用的过程中总不是那么的简便,比如需要引很多包,包与包之间还经常会有冲突,demo并不统一(每一个工程师写出来的mock http的代码有可能都是不一样的)。讲真,我在实践过程中,如果没有工具类从头开始自己写一个http的请求,还是要花很长时间的。

现在,有一个类库帮我们解决了这个问题——Unirest。

 

Unirest的特性

1.能够伪造GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS 这些请求。

2.支持同步/异步请求。

3.支持表单提交,文件上传,自定义实体。

4.支持路径参数

5.支持gzip

6.支持本地的 Basic Authentication

7.自定义超时,并发级别和代理设置。

8.为每个请求自定义默认请求头。

9.自定义HttpClientHttpAsyncClient

10.自动解析JSON

11.自定义的将返回的json数据转换成Java对象。

 

Maven:

<dependency>
    <groupId>com.mashape.unirest</groupId>
    <artifactId>unirest-java</artifactId>
    <version>1.4.9</version>
</dependency>

需要依赖如下的maven:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.3.6</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpasyncclient</artifactId>
  <version>4.0.2</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.3.6</version>
</dependency>
<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20140107</version>
</dependency>

 

创建请求

HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .queryString("apiKey", "123")
  .field("parameter", "value")
  .field("foo", "bar")
  .asJson();

如上,当调用asJson()这个方法的时候,这个post请求就被发送了。不只包含json这种类型,还可以是JSON,Binary,String,Object等类型。

queryString和field比较类似,我理解queryString是get请求中用于拼接问好后面的参数,field用于post请求,但是该类并没有很严格的要求,get和post都可以使用。

 

序列化

如果要求返回的直接是一个Java对象,那么我们需要将json格式的数据转成Java对象,这中间需要一些序列化的工具,个人比较喜欢Gson。

所以,在调用asObject(Class).body(Object)方法 之前,有必要实现一个自定义的ObjectMapper接口。这应该只在第一次完成,因为ObjectMapper的实例将在全局共享。

// Only one time
Unirest.setObjectMapper(new ObjectMapper() {
    private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper
                = new com.fasterxml.jackson.databind.ObjectMapper();
    
    public <T> T readValue(String value, Class<T> valueType) {
        try {
            return jacksonObjectMapper.readValue(value, valueType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String writeValue(Object value) {
        try {
            return jacksonObjectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
});

// Response to Object
HttpResponse<Book> bookResponse = Unirest.get("http://httpbin.org/books/1").asObject(Book.class);
Book bookObject = bookResponse.getBody();

HttpResponse<Author> authorResponse = Unirest.get("http://httpbin.org/books/{id}/author")
    .routeParam("id", bookObject.getId())
    .asObject(Author.class);
    
Author authorObject = authorResponse.getBody();

// Object to Json
HttpResponse<JsonNode> postResponse = Unirest.post("http://httpbin.org/authors/post")
        .header("accept", "application/json")
        .header("Content-Type", "application/json")
        .body(authorObject)
        .asJson();

 

路径参数

可以通过routeParam来设置路径参数,比如:

Unirest.get("http://httpbin.org/{method}")
  .routeParam("method", "get")
  .queryString("name", "Mark")
  .asJson();

{method}这个占位符就会变成get。

 

异步请求

有时候我们需要请求是异步的而不是阻塞的,Unirest支持回调方法,如下:

Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .field("param1", "value1")
  .field("param2", "value2")
  .asJsonAsync(new Callback<JsonNode>() {

    public void failed(UnirestException e) {
        System.out.println("The request has failed");
    }

    public void completed(HttpResponse<JsonNode> response) {
         int code = response.getStatus();
         Map<String, String> headers = response.getHeaders();
         JsonNode body = response.getBody();
         InputStream rawBody = response.getRawBody();
    }

    public void cancelled() {
        System.out.println("The request has been cancelled");
    }

});

 

文件上传

只需将一个File或一个InputStream对象作为字段传递即可,如下:

HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .field("parameter", "value")
  .field("file", new File("/tmp/file"))
  .asJson();

自定义实体

HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
  .header("accept", "application/json")
  .body("{\"parameter\":\"value\", \"foo\":\"bar\"}")
  .asJson();

字节流作为实体

final InputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI()));
final byte[] bytes = new byte[stream.available()];
stream.read(bytes);
stream.close();
final HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
  .field("name", "Mark")
  .field("file", bytes, "image.jpg")
  .asJson();

InputStream作为实体

HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
  .field("name", "Mark")
  .field("file", new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())), ContentType.APPLICATION_OCTET_STREAM, "image.jpg")
  .asJson();

基本认证

通过调用basicAuth(username, password)方法可以通过基本身份验证来验证请求:

HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/headers").basicAuth("username", "password").asJson();

请求

Unirest遵循构建器约定,可以通过一下几种方式来构建一个http请求。

GetRequest request = Unirest.get(String url);
GetRequest request = Unirest.head(String url);
HttpRequestWithBody request = Unirest.post(String url);
HttpRequestWithBody request = Unirest.put(String url);
HttpRequestWithBody request = Unirest.patch(String url);
HttpRequestWithBody request = Unirest.options(String url);
HttpRequestWithBody request = Unirest.delete(String url);

 响应

收到响应后,Unirest以一个对象的形式返回结果,该对象有如下几种 键:

  • .getStatus() – HTTP响应状态代码(例如:200)
  • .getStatusText() – HTTP响应状态文本(示例:“确定”)
  • .getHeaders() – HTTP响应标头
  • .getBody() – 适用的解析响应体,例如JSON响应被解析为Objects / Associative Arrays。
  • .getRawBody() – 未解析的响应正文

高级配置

自定义HTTP客户端

可以使用以下方法显式设置自己的实现HttpClientHttpAsyncClient

Unirest.setHttpClient(httpClient);
Unirest.setAsyncHttpClient(asyncHttpClient);

超时

可以设置自定义连接和套接字超时值(以毫秒为单位):

Unirest.setTimeouts(long connectionTimeout, long socketTimeout);

默认情况下,连接超时(连接到服务器所需的时间)是10000和套接字超时(接收数据所需的时间)是60000,也可以将这些超时中的任何一个设置为零以禁用超时。

默认请求标头

可以设置将在每个请求上发送的默认标头:

Unirest.setDefaultHeader("Header1", "Value1");
Unirest.setDefaultHeader("Header2", "Value2");

也可以清楚这些头信息:

Unirest.clearDefaultHeaders();

并发

如果需要调整同步或异步客户端的性能,可以设置自定义并发级别:

Unirest.setConcurrency(int maxTotal, int maxPerRoute);

默认情况下,maxTotal(池中的总连接限制)200和maxPerRoute(每个目标主机的连接限制)是20

代理

您可以通过调用来设置代理:

Unirest.setProxy(new HttpHost("127.0.0.1", 8000));

退出申请

Unirest启动后台事件循环,在我们通过调用手动关闭所有线程之前,Java应用程序将无法退出:

Unirest.shutdown();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章