使用HttpClient调用接口的实例讲解
一,编写返回对象
publicclassHttpResult{
//响应的状态码
privateintcode;
//响应的响应体
privateStringbody;
get/set…
}
二,封装HttpClient
packagecn.xxxxxx.httpclient;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Map;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpDelete;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.client.methods.HttpPut;
importorg.apache.http.client.utils.URIBuilder;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.util.EntityUtils;
publicclassAPIService{
privateCloseableHttpClienthttpClient;
publicAPIService(){
//1创建HttpClinet,相当于打开浏览器
this.httpClient=HttpClients.createDefault();
}
/**
*带参数的get请求
*
*@paramurl
*@parammap
*@return
*@throwsException
*/
publicHttpResultdoGet(Stringurl,Mapmap)throwsException{
//声明URIBuilder
URIBuilderuriBuilder=newURIBuilder(url);
//判断参数map是否为非空
if(map!=null){
//遍历参数
for(Map.Entryentry:map.entrySet()){
//设置参数
uriBuilder.setParameter(entry.getKey(),entry.getValue().toString());
}
}
//2创建httpGet对象,相当于设置url请求地址
HttpGethttpGet=newHttpGet(uriBuilder.build());
//3使用HttpClient执行httpGet,相当于按回车,发起请求
CloseableHttpResponseresponse=this.httpClient.execute(httpGet);
//4解析结果,封装返回对象httpResult,相当于显示相应的结果
//状态码
//response.getStatusLine().getStatusCode();
//响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
//EntityUtils.toString(response.getEntity(),"UTF-8");
HttpResulthttpResult=null;
//解析数据封装HttpResult
if(response.getEntity()!=null){
httpResult=newHttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(),"UTF-8"));
}else{
httpResult=newHttpResult(response.getStatusLine().getStatusCode(),"");
}
//返回
returnhttpResult;
}
/**
*不带参数的get请求
*
*@paramurl
*@return
*@throwsException
*/
publicHttpResultdoGet(Stringurl)throwsException{
HttpResulthttpResult=this.doGet(url,null);
returnhttpResult;
}
/**
*带参数的post请求
*
*@paramurl
*@parammap
*@return
*@throwsException
*/
publicHttpResultdoPost(Stringurl,Mapmap)throwsException{
//声明httpPost请求
HttpPosthttpPost=newHttpPost(url);
//判断map不为空
if(map!=null){
//声明存放参数的List集合
Listparams=newArrayList();
//遍历map,设置参数到list中
for(Map.Entryentry:map.entrySet()){
params.add(newBasicNameValuePair(entry.getKey(),entry.getValue().toString()));
}
//创建form表单对象
UrlEncodedFormEntityformEntity=newUrlEncodedFormEntity(params,"UTF-8");
//把表单对象设置到httpPost中
httpPost.setEntity(formEntity);
}
//使用HttpClient发起请求,返回response
CloseableHttpResponseresponse=this.httpClient.execute(httpPost);
//解析response封装返回对象httpResult
HttpResulthttpResult=null;
if(response.getEntity()!=null){
httpResult=newHttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(),"UTF-8"));
}else{
httpResult=newHttpResult(response.getStatusLine().getStatusCode(),"");
}
//返回结果
returnhttpResult;
}
/**
*不带参数的post请求
*
*@paramurl
*@return
*@throwsException
*/
publicHttpResultdoPost(Stringurl)throwsException{
HttpResulthttpResult=this.doPost(url,null);
returnhttpResult;
}
/**
*带参数的Put请求
*
*@paramurl
*@parammap
*@return
*@throwsException
*/
publicHttpResultdoPut(Stringurl,Mapmap)throwsException{
//声明httpPost请求
HttpPuthttpPut=newHttpPut(url);
//判断map不为空
if(map!=null){
//声明存放参数的List集合
Listparams=newArrayList();
//遍历map,设置参数到list中
for(Map.Entryentry:map.entrySet()){
params.add(newBasicNameValuePair(entry.getKey(),entry.getValue().toString()));
}
//创建form表单对象
UrlEncodedFormEntityformEntity=newUrlEncodedFormEntity(params,"UTF-8");
//把表单对象设置到httpPost中
httpPut.setEntity(formEntity);
}
//使用HttpClient发起请求,返回response
CloseableHttpResponseresponse=this.httpClient.execute(httpPut);
//解析response封装返回对象httpResult
HttpResulthttpResult=null;
if(response.getEntity()!=null){
httpResult=newHttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(),"UTF-8"));
}else{
httpResult=newHttpResult(response.getStatusLine().getStatusCode(),"");
}
//返回结果
returnhttpResult;
}
/**
*带参数的Delete请求
*
*@paramurl
*@parammap
*@return
*@throwsException
*/
publicHttpResultdoDelete(Stringurl,Mapmap)throwsException{
//声明URIBuilder
URIBuilderuriBuilder=newURIBuilder(url);
//判断参数map是否为非空
if(map!=null){
//遍历参数
for(Map.Entryentry:map.entrySet()){
//设置参数
uriBuilder.setParameter(entry.getKey(),entry.getValue().toString());
}
}
//2创建httpGet对象,相当于设置url请求地址
HttpDeletehttpDelete=newHttpDelete(uriBuilder.build());
//3使用HttpClient执行httpGet,相当于按回车,发起请求
CloseableHttpResponseresponse=this.httpClient.execute(httpDelete);
//4解析结果,封装返回对象httpResult,相当于显示相应的结果
//状态码
//response.getStatusLine().getStatusCode();
//响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
//EntityUtils.toString(response.getEntity(),"UTF-8");
HttpResulthttpResult=null;
//解析数据封装HttpResult
if(response.getEntity()!=null){
httpResult=newHttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(),"UTF-8"));
}else{
httpResult=newHttpResult(response.getStatusLine().getStatusCode(),"");
}
//返回
returnhttpResult;
}
}
三,调用接口
packagecn.xxxxxx.httpclient.test;
importjava.util.HashMap;
importjava.util.Map;
importorg.junit.Before;
importorg.junit.Test;
importcn.itcast.httpclient.APIService;
importcn.itcast.httpclient.HttpResult;
publicclassAPIServiceTest{
privateAPIServiceapiService;
@Before
publicvoidinit(){
this.apiService=newAPIService();
}
//查询
@Test
publicvoidtestQueryItemById()throwsException{
//http://manager.aaaaaa.com/rest/item/interface/{id}
Stringurl="http://manager.aaaaaa.com/rest/item/interface/42";
HttpResulthttpResult=this.apiService.doGet(url);
System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody());
}
//新增
@Test
publicvoidtestSaveItem()throwsException{
//http://manager.aaaaaa.com/rest/item/interface/{id}
Stringurl="http://manager.aaaaaa.com/rest/item/interface";
Mapmap=newHashMap();
//title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1
map.put("title","测试APIService调用新增接口");
map.put("price","1000");
map.put("num","1");
map.put("cid","666");
map.put("status","1");
HttpResulthttpResult=this.apiService.doPost(url,map);
System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody());
}
//修改
@Test
publicvoidtestUpdateItem()throwsException{
//http://manager.aaaaaa.com/rest/item/interface/{id}
Stringurl="http://manager.aaaaaa.com/rest/item/interface";
Mapmap=newHashMap();
//title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1
map.put("title","测试APIService调用修改接口");
map.put("id","44");
HttpResulthttpResult=this.apiService.doPut(url,map);
System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody());
}
//删除
@Test
publicvoidtestDeleteItemById()throwsException{
//http://manager.aaaaaa.com/rest/item/interface/{id}
Stringurl="http://manager.aaaaaa.com/rest/item/interface/44";
HttpResulthttpResult=this.apiService.doDelete(url,null);
System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody());
}
}
以上这篇使用HttpClient调用接口的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。