使用HttpClient访问接口(Rest接口和普通接口)
这里总结一下使用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接口和普通接口)的更多相关文章
- java实现利用httpclient访问接口
HTTP协议时Internet上使用的很多也很重要的一个协议,越来越多的java应用程序需要通过HTTP协议来访问网络资源. HTTPClient提供的主要功能: 1.实现了所有HTTP的方法(GET ...
- 使用httpclient访问NLP应用接口例子
参考网址: http://yuzhinlp.com/docs.html 接入前须知 接入条件 1.进入网站首页,点击注册成为语知科技用户 2.注册完成后,系统将提供语知科技用户唯一标识APIKey,并 ...
- 【经验随笔】Java通过代理访问互联网平台提供的WebService接口的一种方法
背景 通常有两点原因需要通过代理访问互联网平台的提供的WebService接口: 1. 在公司企业内网访问外部互联网平台发布的接口,公司要求通过代理访问外网. 2. 频繁访问平台接口,IP被平台封了, ...
- Java基础进阶:多态与接口重点摘要,类和接口,接口特点,接口详解,多态详解,多态中的成员访问特点,多态的好处和弊端,多态的转型,多态存在的问题,附重难点,代码实现源码,课堂笔记,课后扩展及答案
多态与接口重点摘要 接口特点: 接口用interface修饰 interface 接口名{} 类实现接口用implements表示 class 类名 implements接口名{} 接口不能实例化,可 ...
- cxf整合spring发布rest服务 httpclient访问服务
1.创建maven web项目并添加依赖 pom.xml <properties> <webVersion>3.0</webVersion> <cxf.ver ...
- Surface Pro 4 和 Surface Book 使用名为 Surface UEFI(统一可扩展固件接口)的新固件接口
Surface Pro 4 和 Surface Book 使用名为 Surface UEFI(统一可扩展固件接口)的新固件接口.Surface UEFI 提供新功能,如启动更快速.安全性更高.可替换 ...
- PHP做APP接口时,如何保证接口的安全性??????????
PHP做APP接口时,如何保证接口的安全性? 1.当用户登录APP时,使用https协议调用后台相关接口,服务器端根据用户名和密码时生成一个access_key,并将access_key保存在sess ...
- java接口对接——别人调用我们接口获取数据
java接口对接——别人调用我们接口获取数据,我们需要在我们系统中开发几个接口,给对方接口规范文档,包括访问我们的接口地址,以及入参名称和格式,还有我们的返回的状态的情况, 接口代码: package ...
- C#显示接口实现和隐式接口实现
在项目中可能会遇到显示接口实现和隐式接口实现.什么意思呢?简单来说使用接口名作为方法名的前缀,这称为“显式接口实现”:传统的实现方式,称为“隐式接口实现”.隐式接口实现如下: interface IS ...
随机推荐
- Livy 安装教程
Livy 安装教程 本文原始地址:https://sitoi.cn/posts/16143.html 安装环境 Fedora 29 Spark PySpark 安装步骤 下载 Livy 安装包 解压 ...
- python之线程和进程(并发编程)
python的GIL In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native ...
- React源码 memo Fragment StrictMode cloneElement createFactory
1.memo react 16.6 推出的 api ,他的用意是给 function component 也有 PureComponent 这样一个类似的功能,因为我们知道 PureComponent ...
- 性能测试基础---ant集成2
·自定义报告模板:因为默认的ant提供的报告模板,是没有tps和90%line这样的数据.但是在实际工作中,这两个统计数据又是必须的,那么我们可以通过自定义(修改)的方式来进行修改,达到我们的目的. ...
- 关于pytest的命令行传参
#conftest.py import pytest def pytest_addoption(parser): #parser:用户命令行参数与ini文件值的解析器 # group = parser ...
- jieba模块
jieba模块 下载 pip install jieba 使用 import jieba 精确模式 jieba.cut() 直接打印出的是单个文字 转换成列表-->jieba.lcut() im ...
- 小学四则运算口算练习app---No.6
今天主要解决按钮的闪退问题以及答案页面的设置: (位置问题还是无能为力....) 除此之外加了一些菜单键,右上角 resultActivity.class ; String select=;i< ...
- 转 Git生成SSH
SSH keys SSH key 可以让你在你的电脑和Code服务器之间建立安全的加密连接. 先执行以下语句来判断是否已经存在本地公钥: cat ~/.ssh/id_rsa.pub 如果你看到一长串以 ...
- Codeforces 379F New Year Tree
F. New Year Tree time limit per test2 seconds memory limit per test256 megabytes You are a programme ...
- nuxtjs如何通过路由meta信息控制路由查看权限
我们知道NUXTJS可以通过路由中间件进行路由鉴权,中间件允许您定义一个自定义函数运行在一个页面或一组页面渲染之前. 但是我在实际使用过程中发现,中间件只有在路由跳转到路由中时才会进入,而在强制刷新网 ...