Unirest for Java

18 篇文章 0 订阅
13 篇文章 0 订阅

在这里插入图片描述
http://unirest.io/java.html

通常利用httpclient处理网络请求,大体方式如下,

public String doGet(String url) {

        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;
        try{
            httpClient = HttpClients.createDefault();
            httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,"UTF-8");
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }

        return result;
    }

最近接触JIRA平台的API时,发现他们都是用Unirest来完成请求,因此了解下Unirest库是如何使用的

public String doGet(String url) {

        HttpResponse jsonResponse = null;
        try {
            jsonResponse = Unirest.get(url).asString();
        } catch (UnirestException e) {
            e.printStackTrace();
        }

        return jsonResponse.getBody().toString();
    }

上面分别测试两种方式的get请求,同时请求一个URL,返回结果相同:

httpclient request:
<!DOCTYPE HTML>

<html>
<head>
    <title>Home Pages</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
        <p>Hello World!</p>
    <p>Version:v001-2015-09-24-pm</p>
    <p>Release:2015/10/10 10:24</p>
    <p>Environment:Production Environment</p>
    <p>Timestamp:2018-11-11 22:32:13</p>
</body>
</html>
unirest request:
<!DOCTYPE HTML>

<html>
<head>
    <title>Home Pages</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
        <p>Hello World!</p>
    <p>Version:v001-2015-09-24-pm</p>
    <p>Release:2015/10/10 10:24</p>
    <p>Environment:Production Environment</p>
    <p>Timestamp:2018-11-11 22:32:13</p>
</body>
</html>

不管使用httpclient完成网络请求,还是使用unirest实现网络请求,效果均一样,但从代码简洁度上看,unirest更加简洁,能够使用较少的代码完成请求,unirest定位是一个轻量级的http库,在日常工作中可以融入进来,处理问题多一种方式。

本文仅浅显介绍了unirest用法,更全面的使用说明请上官网查看。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值