一,编写返回对象

public class HttpResult {
// 响应的状态码
private int code;

// 响应的响应体
private String body;
get/set…
}

二,封装HttpClient

package cn.xxxxxx.httpclient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; public class APIService { private CloseableHttpClient httpClient; public APIService() {
// 1 创建HttpClinet,相当于打开浏览器
this.httpClient = HttpClients.createDefault();
} /**
* 带参数的get请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doGet(String url, Map<String, Object> map) throws Exception { // 声明URIBuilder
URIBuilder uriBuilder = new URIBuilder(url); // 判断参数map是否为非空
if (map != null) {
// 遍历参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
// 设置参数
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
} // 2 创建httpGet对象,相当于设置url请求地址
HttpGet httpGet = new HttpGet(uriBuilder.build()); // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
CloseableHttpResponse response = this.httpClient.execute(httpGet); // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
// 状态码
// response.getStatusLine().getStatusCode();
// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
// EntityUtils.toString(response.getEntity(), "UTF-8");
HttpResult httpResult = null;
// 解析数据封装HttpResult
if (response.getEntity() != null) {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
} else {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
} // 返回
return httpResult;
} /**
* 不带参数的get请求
*
* @param url
* @return
* @throws Exception
*/
public HttpResult doGet(String url) throws Exception {
HttpResult httpResult = this.doGet(url, null);
return httpResult;
} /**
* 带参数的post请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url); // 判断map不为空
if (map != null) {
// 声明存放参数的List集合
List<NameValuePair> params = new ArrayList<NameValuePair>(); // 遍历map,设置参数到list中
for (Map.Entry<String, Object> entry : map.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
} // 创建form表单对象
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8"); // 把表单对象设置到httpPost中
httpPost.setEntity(formEntity);
} // 使用HttpClient发起请求,返回response
CloseableHttpResponse response = this.httpClient.execute(httpPost); // 解析response封装返回对象httpResult
HttpResult httpResult = null;
if (response.getEntity() != null) {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
} else {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
} // 返回结果
return httpResult;
} /**
* 不带参数的post请求
*
* @param url
* @return
* @throws Exception
*/
public HttpResult doPost(String url) throws Exception {
HttpResult httpResult = this.doPost(url, null);
return httpResult;
} /**
* 带参数的Put请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
// 声明httpPost请求
HttpPut httpPut = new HttpPut(url); // 判断map不为空
if (map != null) {
// 声明存放参数的List集合
List<NameValuePair> params = new ArrayList<NameValuePair>(); // 遍历map,设置参数到list中
for (Map.Entry<String, Object> entry : map.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
} // 创建form表单对象
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8"); // 把表单对象设置到httpPost中
httpPut.setEntity(formEntity);
} // 使用HttpClient发起请求,返回response
CloseableHttpResponse response = this.httpClient.execute(httpPut); // 解析response封装返回对象httpResult
HttpResult httpResult = null;
if (response.getEntity() != null) {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
} else {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
} // 返回结果
return httpResult;
} /**
* 带参数的Delete请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doDelete(String url, Map<String, Object> map) throws Exception { // 声明URIBuilder
URIBuilder uriBuilder = new URIBuilder(url); // 判断参数map是否为非空
if (map != null) {
// 遍历参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
// 设置参数
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
} // 2 创建httpGet对象,相当于设置url请求地址
HttpDelete httpDelete = new HttpDelete(uriBuilder.build()); // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
CloseableHttpResponse response = this.httpClient.execute(httpDelete); // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
// 状态码
// response.getStatusLine().getStatusCode();
// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
// EntityUtils.toString(response.getEntity(), "UTF-8");
HttpResult httpResult = null;
// 解析数据封装HttpResult
if (response.getEntity() != null) {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
} else {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
} // 返回
return httpResult;
} }

三,调用接口

package cn.xxxxxx.httpclient.test;

import java.util.HashMap;
import java.util.Map; import org.junit.Before;
import org.junit.Test; import cn.itcast.httpclient.APIService;
import cn.itcast.httpclient.HttpResult; public class APIServiceTest { private APIService apiService; @Before
public void init() {
this.apiService = new APIService();
} // 查询
@Test
public void testQueryItemById() throws Exception {
// http://manager.aaaaaa.com/rest/item/interface/{id} String url = "http://manager.aaaaaa.com/rest/item/interface/42"; HttpResult httpResult = this.apiService.doGet(url); System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody()); } // 新增
@Test
public void testSaveItem() throws Exception {
// http://manager.aaaaaa.com/rest/item/interface/{id} String url = "http://manager.aaaaaa.com/rest/item/interface"; Map<String, Object> map = new HashMap<String, Object>();
// 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"); HttpResult httpResult = this.apiService.doPost(url, map); System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody()); } // 修改 @Test
public void testUpdateItem() throws Exception {
// http://manager.aaaaaa.com/rest/item/interface/{id} String url = "http://manager.aaaaaa.com/rest/item/interface"; Map<String, Object> map = new HashMap<String, Object>();
// title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1
map.put("title", "测试APIService调用修改接口");
map.put("id", "44"); HttpResult httpResult = this.apiService.doPut(url, map); System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody()); } // 删除
@Test
public void testDeleteItemById() throws Exception {
// http://manager.aaaaaa.com/rest/item/interface/{id} String url = "http://manager.aaaaaa.com/rest/item/interface/44"; HttpResult httpResult = this.apiService.doDelete(url, null); System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody()); } }

使用HttpClient调用接口的更多相关文章

  1. httpClient调用接口的时候,解析返回报文内容

    比如我httpclient调用的接口返回的格式是这样的: 一:data里是个对象 { "code": 200, "message": "执行成功&qu ...

  2. 使用httpClient调用接口,参数用map封装或者使用JSON参数,并转换返回结果

    这里接口用表存起来,标记请求方式,然后接受参数,消息或者请求参数都可以, 然后先是遍历需要调用的接口,封装参数,再分别调用get与post即可,没有微服务还是得自己写 //消息转发-获取参数中对应参数 ...

  3. java通过HttpClient调用接口总结

    2.HttpClient 2.1简介: 最近看项目的代码,看到工程中有两个jar包张的很像,一个是commons.httpclient-3.1.jar,一个是httpclient4.2.1.jar,很 ...

  4. 使用httpClient调用接口获取响应数据

    转自:https://blog.csdn.net/shuaishuaidewo/article/details/81136088 import lombok.extern.slf4j.Slf4j; i ...

  5. 使用HttpClient调用第三方接口

    最近项目中需要调用第三方的Http接口,这里我用到了HttpClient. 首先我们要搞明白第三方接口中需要我们传递哪些参数.数据,搞明白参数以后我们就可以使用HttpClient调用接口了. 1.调 ...

  6. 使用HttpClient访问接口(Rest接口和普通接口)

    这里总结一下使用HttpClient访问外部接口的用法.后期如果发现有什么缺陷会更改.欢迎读者指出此方法的不足之处. 首先,创建一个返回实体: public class HttpResult { // ...

  7. springMVC、httpClient调用别人提供的接口!!!(外加定时调用)

    import com.ibm.db.util.AppConfig; import com.ibm.db.util.JacksonUitl; import org.apache.http.HttpEnt ...

  8. HttpClient方式调用接口的实例

    使用HttpClient的方式调用接口的实例. public class TestHttpClient { public static void main(String[] args) { // 请求 ...

  9. 服务端调用接口API利器之HttpClient

    前言 之前有介绍过HttpClient作为爬虫的简单使用,那么今天在简单的介绍一下它的另一个用途:在服务端调用接口API进行交互.之所以整理这个呢,是因为前几天在测试云之家待办消息接口的时候,有使用云 ...

随机推荐

  1. MySQL中IS NULL、IS NOT NULL、!=不能用索引?胡扯!

    转:https://mp.weixin.qq.com/s/CEJFsDBizdl0SvugGX7UmQ 不知道从什么时候开始,网上流传着这么一个说法: MySQL的WHERE子句中包含 IS NULL ...

  2. RSA算法java实现(BigInteger类的各种应用)

    一.RSA算法 1.密钥生成 随机生成两个大素数p.q 计算n=p*q 计算n的欧拉函数f=(p-1)*(q-1) 选取1<e<f,使e与f互素 计算d,ed=1modf 公钥为(e,n) ...

  3. unity序列化

    什么是序列化 unity的序列化在unity的开发中起着举重足轻的地位,许多核心的功能都是基于序列化和反序列化来实现的.序列化简单来讲就是就是将我们所要保存的数据进行二进制存储,然后当我们需要的时候, ...

  4. abp中使用同步方法调用异步方法

    var result= AsyncHelper.RunSync(()=>{   return  _service.GetUserAsync();   });

  5. 坐标转换7参数计算工具——arcgis 地理处理工具案例教程

    坐标转换7参数计算工具--arcgis 地理处理工具案例教程 商务合作,科技咨询,版权转让:向日葵,135-4855_4328,xiexiaokui#qq.com 不接受个人免费咨询. 提供API,独 ...

  6. HandlerMethodReturnValueHandler SpringMVC 参数解析 继承关系以及各解析器解析类型

    I HandlerMethodReturnValueHandler (org.springframework.web.method.support) AbstractMessageConverterM ...

  7. Linux 等待信号(sigsuspend)

    /* sigsuspend()函数说明 */ #include <stdio.h> #include <signal.h> /* 知识补充: sigsuspend()函数 函数 ...

  8. 利用nvidia-smi 管理和监控NVIDIA GPU设备

    NVIDIA系统管理界面介绍 原文来源:https://developer.nvidia.com/nvidia-system-management-interface NVIDIA系统管理界面(nvi ...

  9. PHP 指定时间/时间戳+某天/某月/某年

    PHP指定时间戳加上1天,1周,1月,一年其实是不需要用上什么函数的!指定时间戳本身就是数字整型,我们只需要再计算1天,1周它的秒数相加即可! 博主搜索php指定时间戳加一天一年,结果许多的文章给出来 ...

  10. ShenZhenXiaoLengHuanYou Technology Co.,Ltd 技术支持网站

    本网页为ShenZhenXiaoLengHuanYou Technology Co.,Ltd 团队的技术支持网址,如果在我们开发的游戏中遇到任何问题,欢迎联系我们! QQ:2535510006 邮箱: ...