通常利用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用法,更全面的使用说明请上官网查看。