这里总结一下使用HttpClient访问外部接口的用法。后期如果发现有什么缺陷会更改。欢迎读者指出此方法的不足之处。

首先,创建一个返回实体:

public class HttpResult {
// 响应的状态码
private int code; // 响应的响应体
private String body; public HttpResult(int code, String body) {
this.code = code;
this.body = body;
}
//省略get/set
}

创建一个HttpClientUtil:

public class HttpClientUtil {

    private static CloseableHttpClient httpClient =  HttpClients.createDefault();	//用static实现单例,此处不完善,当多线程时会出现问题。

    /**
* 带参数的get请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public static 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 = 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 static HttpResult doGet(String url) throws Exception {
HttpResult httpResult = doGet(url, null);
return httpResult;
} /**
* 带参数的post请求
*
* @param url
* @return
* @throws Exception
*/
public static HttpResult doPost(String url, Map<String, Object> reqMap, Map<String,String> headersMap) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
for (Map.Entry<String, String> entry: headersMap.entrySet())
httpPost.addHeader(entry.getKey(), entry.getValue()); // 判断map不为空
if (reqMap != null) { // 创建form表单对象
StringEntity formEntity = new StringEntity(JSON.toJSONString(reqMap), "UTF-8"); // 把表单对象设置到httpPost中
httpPost.setEntity(formEntity);
} // 使用HttpClient发起请求,返回response
CloseableHttpResponse response = 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 static HttpResult doPost(String url) throws Exception {
HttpResult httpResult = doPost(url, null,null);
return httpResult;
} /**
* 带参数的Put请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public static 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 = 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 static 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 = 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;
} /**
* 返回常用请求头
* @return
*/
public static Map<String, String> commentHeader(){
Map<String, String> map = new HashMap<>();
map.put("Content-Type", "application/json");
return map;
}
}

测试一下:

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 { // 查询
@Test
public void testGet() throws Exception {
// http://manager.aaaaaa.com/rest/item/interface/{id} String url = "http://manager.aaaaaa.com/rest/item/interface/42"; HttpResult httpResult = HttpClientUtil.doGet(url); System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody()); } // 查询
@Test
public void testPost() throws Exception {
//设置参数
Map reqMap = new HashMap();
reqMap.put("distCode", arsArg.getDistCode());
HttpResult httpResult = null;
try {
//RestUrlsCommons.RMDS_DISTRICT_FINDBYDISTCODE为url
//reqMap:请求参数
//HttpClientUtil.commentHeader():请求头
httpResult = HttpClientUtil.doPost(RestUrlsCommons.RMDS_DISTRICT_FINDBYDISTCODE, reqMap, HttpClientUtil.commentHeader());
} catch (Exception e) {
e.printStackTrace();
} System.out.println(httpResult.getCode());
System.out.println(httpResult.getBody());
} }

参考资料:使用HttpClient调用接口

使用HttpClient访问接口(Rest接口和普通接口)的更多相关文章

  1. java实现利用httpclient访问接口

    HTTP协议时Internet上使用的很多也很重要的一个协议,越来越多的java应用程序需要通过HTTP协议来访问网络资源. HTTPClient提供的主要功能: 1.实现了所有HTTP的方法(GET ...

  2. 使用httpclient访问NLP应用接口例子

    参考网址: http://yuzhinlp.com/docs.html 接入前须知 接入条件 1.进入网站首页,点击注册成为语知科技用户 2.注册完成后,系统将提供语知科技用户唯一标识APIKey,并 ...

  3. 【经验随笔】Java通过代理访问互联网平台提供的WebService接口的一种方法

    背景 通常有两点原因需要通过代理访问互联网平台的提供的WebService接口: 1. 在公司企业内网访问外部互联网平台发布的接口,公司要求通过代理访问外网. 2. 频繁访问平台接口,IP被平台封了, ...

  4. Java基础进阶:多态与接口重点摘要,类和接口,接口特点,接口详解,多态详解,多态中的成员访问特点,多态的好处和弊端,多态的转型,多态存在的问题,附重难点,代码实现源码,课堂笔记,课后扩展及答案

    多态与接口重点摘要 接口特点: 接口用interface修饰 interface 接口名{} 类实现接口用implements表示 class 类名 implements接口名{} 接口不能实例化,可 ...

  5. cxf整合spring发布rest服务 httpclient访问服务

    1.创建maven web项目并添加依赖 pom.xml <properties> <webVersion>3.0</webVersion> <cxf.ver ...

  6. Surface Pro 4 和 Surface Book 使用名为 Surface UEFI(统一可扩展固件接口)的新固件接口

    Surface Pro 4 和 Surface Book 使用名为 Surface UEFI(统一可扩展固件接口)的新固件接口.Surface UEFI 提供新功能,如启动更快速.安全性更高.可替换 ...

  7. PHP做APP接口时,如何保证接口的安全性??????????

    PHP做APP接口时,如何保证接口的安全性? 1.当用户登录APP时,使用https协议调用后台相关接口,服务器端根据用户名和密码时生成一个access_key,并将access_key保存在sess ...

  8. java接口对接——别人调用我们接口获取数据

    java接口对接——别人调用我们接口获取数据,我们需要在我们系统中开发几个接口,给对方接口规范文档,包括访问我们的接口地址,以及入参名称和格式,还有我们的返回的状态的情况, 接口代码: package ...

  9. C#显示接口实现和隐式接口实现

    在项目中可能会遇到显示接口实现和隐式接口实现.什么意思呢?简单来说使用接口名作为方法名的前缀,这称为“显式接口实现”:传统的实现方式,称为“隐式接口实现”.隐式接口实现如下: interface IS ...

随机推荐

  1. jieba模块

    jieba模块 下载 pip install jieba 使用 import jieba 精确模式 jieba.cut() 直接打印出的是单个文字 转换成列表-->jieba.lcut() im ...

  2. ActiveMQ消息可靠性-事物

    事物偏生产者,签收偏消费者 设置为true,需要手动提交    设置为false,自动提交   使用手动提交的好处就是可以回滚,当整个事物提交时,里面的某条失败了,可以事物回滚,于是保证了数据的一致性 ...

  3. janusgraph的数据模型

    janusgraph的数据模型--->参考 1.简介 janusgraph的数据模型,就是一数据结构中得图结构相似.所以janusgraph的数据schema主要定义在三个要素上:顶点,边,属性 ...

  4. Linux-day02

    一.安装搜狗输入法 1.更新包安装 setting→language support 2.安装中文语言包,安装Fcitx输入法框架 3.安装搜狗输入法命令: sudo dpkg -i sogoupin ...

  5. selenium--加载浏览器配置

    前戏 在我们之前写的自动化脚本中,不知道大家有没有发现,每次打开的都是一个新的浏览器(相当于新安装的).但是有时候,我们想打开的是我们配置好的浏览器.我在之前的公司做web自动化的时候,由于我们的网站 ...

  6. p1842 奶牛玩杂技 题解

    感觉其他dalao讲的不是很明白啊,我这样的蒟蒻看不懂啊. 在luogu这个dalao遍地的地方我蒟蒻看个题解也不明白,我为跟我同病相怜的蒟蒻写一篇吧 其实真是不太明白,大部分题解都是只说 体重大的在 ...

  7. 【DP】【P5615】 [MtOI2019] 时间跳跃

    Description 给定 \(n\) 条边,第 \(i\) 条边的长度为 \(i\),每条边都有 \(50\%\) 的概率被选择,求如果选出的边能组成一个平面凸多边形,则方案的权值是方案中边的数量 ...

  8. day 18

    Only through experience of trial and suffering can the soul be strengthened, vision cleared, ambitio ...

  9. PATB1048数字加密

    关于代码都是可以在PAT上跑通的 自己是在VS2017上写的,所以会有语句system("pause");,表示暂定方便查看结果. *在一个是VS2017中使用scanf会报错,所 ...

  10. zabbix解决监控图形中文乱码

    原文: https://blog.csdn.net/xujiamin0022016/article/details/86541783 zabbix 4解决监控图形中文乱码首先在windows里找到你想 ...