通过httpClient来完成系统间的服务调用

1.什么是HttpClient

HttpClient是Apache提供的HTTP网络访问接口,HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient.

2.具体实现

带参数和不带参数的post,get请求,json的post请求

这里将功能实现封装为一个工具类,具体如下:

publicclassHttpClientUtils

{

/**

*携带请求参数的GET请求

*/

publicstaticString

doGet(Stringurl, Mapparam) {

Stringresult="";

// 1.创建Httpclient对象

CloseableHttpClienthttpclient= HttpClients.createDefault();

CloseableHttpResponseresponse=null;

try{

// 2.创建uri对象

URIBuilderbuilder=newURIBuilder(url);

if(param!=null) {

for(Stringkey:param.keySet()) {

builder.addParameter(key,param.get(key));

}

}

URIuri=builder.build();

// 3.创建httpGET请求

HttpGethttpGet=newHttpGet(uri);

// 4.执行请求

response=httpclient.execute(httpGet);

// 5.判断返回状态是否为200

if(response.getStatusLine().getStatusCode() == 200) {

// 6.进行UTF-8编码处理

result= EntityUtils.toString(response.getEntity(),"UTF-8");

}

}catch(Exceptione) {

e.printStackTrace();

}finally{

try{

if(response!=null) {

response.close();

}

httpclient.close();

}catch(IOExceptione) {

e.printStackTrace();

}

}

returnresult;

}

/**

*不需要携带参数的get请求

*/

publicstaticString

doGet(Stringurl) {

returndoGet(url,null);

}

/**

*携带请求参数的POST请求

*/

publicstaticString

doPost(Stringurl, Mapparam) {

Stringresult="";

// 1.创建Httpclient对象

CloseableHttpClienthttpClient= HttpClients.createDefault();

CloseableHttpResponseresponse=null;

try{

// 2.创建HttpPost请求

HttpPosthttpPost=newHttpPost(url);

// 3.创建参数列表

if(param!=null) {

ListparamList=newArrayList<>();

for(Stringkey:param.keySet()) {

paramList.add(newBasicNameValuePair(key,param.get(key)));

}

// 4.模拟表单

UrlEncodedFormEntityentity=newUrlEncodedFormEntity(paramList);

httpPost.setEntity(entity);

}

// 5.执行http请求

response=httpClient.execute(httpPost);

// 6.获取响应的结果

result= EntityUtils.toString(response.getEntity(),"utf-8");

}catch(Exceptione) {

e.printStackTrace();

}finally{

try{

response.close();

}catch(IOExceptione) {

e.printStackTrace();

}

}

returnresult;

}

/**

*发送无携带请求参数的POST请求

*/

publicstaticString

doPost(Stringurl) {

returndoPost(url,null);

}

/**

*以json的方式传递请求参数,发送POST请求

*/

publicstaticString

doPostJson(Stringurl, Stringjson) {

Stringresult="";

// 1.创建Httpclient对象

CloseableHttpClienthttpClient= HttpClients.createDefault();

CloseableHttpResponseresponse=null;

try{

// 2.创建HttpPost请求

HttpPosthttpPost=newHttpPost(url);

// 3.创建请求内容

StringEntityentity=newStringEntity(json, ContentType.APPLICATION_JSON);

httpPost.setEntity(entity);

// 4.执行http请求

response=httpClient.execute(httpPost);

// 5.获取响应结果

result= EntityUtils.toString(response.getEntity(),"utf-8");

}catch(Exceptione) {

e.printStackTrace();

}finally{

try{

response.close();

}catch(IOExceptione) {

e.printStackTrace();

}

}

returnresult;

}

}

你可能感兴趣的:(通过httpClient来完成系统间的服务调用)