HTTP工具

简介: 封装HTTP/HTTPS的GET、POST请求工具,支持自定义Header(如Authorization、Content-Type等),含连接超时配置与SSL安全连接处理,适用于接口通信,自动解析响应为JSON对象,日志记录完整,资源及时释放。

HTTP-GET带header请求
// authorization为授权验证,若无授权验证可删除
private static JSONObject sendGet(String url, String authorization) throws IOException {
CloseableHttpClient cHttpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
get.addHeader("Content-Type", "application/json");
get.addHeader("Authorization", authorization);
CloseableHttpResponse response = cHttpClient.execute(get);
logger.info("Http Comunication end ! code --> " + response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
logger.info("URL=" + url + ",response=" + responseContent);
response.close();
cHttpClient.close();
return JSONObject.parseObject(responseContent);
}
HTTP-POST带header请求
private static JSONObject sendPost(String businessUrl, JSONObject sendMsgBody, String accessToken) throws IOException {
CloseableHttpClient cHttpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(businessUrl);
post.addHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Bearer " + accessToken);
post.setEntity(new StringEntity(sendMsgBody.toString(), "UTF-8"));
CloseableHttpResponse response = cHttpClient.execute(post);
logger.info("Http Comunication end ! code --> " + response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
logger.info("URL=" + businessUrl + ",response=" + responseContent);
response.close();
cHttpClient.close();
return JSONObject.parseObject(responseContent);
}
HTTPS-POST带header请求
//设置链接超时和请求超时等参数,否则会长期停止或者崩溃
private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();

public static String sendHttpsPost(String url, JSONObject params) {
String responseContent = null;
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(url);
// header
httpPost.addHeader("AppKey", SystemConstants.APP_KEY);
httpPost.addHeader("Secret", SystemConstants.SECRET);
// body
httpPost.setEntity(new StringEntity(params.toString(), "UTF-8"));
httpClient = HttpClients.custom().setSSLSocketFactory(createSslConnSocketFactory()).setDefaultRequestConfig(requestConfig).build();
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
responseContent = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(null != httpResponse) {
httpResponse.close();
}
if (null != httpClient) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}

/**

 * 创建SSL安全连接
 * @return SSLConnectionSocketFactory
 */

private static SSLConnectionSocketFactory createSslConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }

        @Override
        public void verify(String host, SSLSocket ssl) {
        }

        @Override
        public void verify(String host, X509Certificate cert) {
        }

        @Override
        public void verify(String host, String[] cns, String[] subjectAlts) {
        }
    });
} catch (GeneralSecurityException e) {
    e.printStackTrace();
}
return sslsf;

}

目录
相关文章
|
前端开发 Java Maven
frontend-maven-plugin
frontend-maven-plugin
1096 1
|
Java 数据安全/隐私保护 数据格式
Spring Cloud Gateway 网关整合 Knife4j 4.3 实现微服务接口文档聚合
Spring Cloud Gateway 网关整合 Knife4j 4.3 实现微服务接口文档聚合
|
2月前
|
关系型数据库 MySQL Linux
Docker下载加速
通过配置网易数帆、阿里云镜像加速器或Docker代理,可显著提升Docker镜像下载速度。推荐使用阿里云加速器,配置简单,支持官方镜像标签;也可结合代理实现更高效拉取。
166 0
|
2月前
|
Java 大数据 Apache
Excel工具-HUTOOL-输出Excel
基于Hutool与Apache POI,封装Excel写入功能,提供ExcelWriter和BigExcelWriter,支持List、Map、Bean等数据类型导出,可自定义样式、多Sheet操作,并避免内存溢出,适用于高效生成Excel文件及Web下载场景。
156 0
|
2月前
|
Web App开发 JavaScript Java
SpringBoot跨域处理
本文介绍了跨域(CORS)问题的产生原因及解决方案。当协议、域名、端口不同时,请求即为跨域。浏览器因同源策略限制,默认阻止跨域请求。通过使用`@CrossOrigin`注解、全局配置`WebMvcConfigurer`或自定义`Filter`添加响应头,可实现跨域资源共享。示例展示了Spring Boot中三种解决CORS的方法,并验证其有效性。
140 0
|
2月前
|
XML 存储 SQL
SpringBoot整合Logback,滚动记录+多文件
logback-spring.xml配置文件实现日志分级输出,支持控制台、文件滚动存储,按模块(如SQL、支付、任务等)分离日志,通过LogProxy获取指定名称的Logger,便于定位问题。配置灵活,适用于多环境部署。
54 0
|
2月前
|
关系型数据库 MySQL 数据库
Docker安装Mysql
本文介绍Docker安装MySQL 5.7的完整流程,涵盖单机部署与主从复制。通过容器卷映射解决中文乱码与数据持久化问题,并详细演示主从配置步骤,实现数据同步,适用于生产环境搭建与学习参考。
130 0
|
2月前
|
网络协议 关系型数据库 MySQL
nexus搭建docker私仓 使用nexus创建docker私有仓库
本文介绍如何使用Nexus搭建Docker私有仓库,包括Nexus中启用Docker仓库、创建Blob存储、配置docker-hosted仓库及端口设置,并说明防火墙开放与Docker客户端配置insecure-registry的方法,实现镜像的推送与拉取。
185 0
|
2月前
|
安全 Linux Shell
Docker镜像
镜像是包含软件运行所需代码、依赖库、配置等的轻量级可执行包。Docker利用联合文件系统实现分层结构,通过bootfs和rootfs构成镜像底层,支持镜像共享与复用。容器启动时在镜像顶层添加可写容器层,所有修改仅作用于该层,保障镜像安全与高效。
82 0
|
SQL 索引
在 SQL Server 中使用 STRING_AGG 函数
【8月更文挑战第5天】
4100 2
在 SQL Server 中使用 STRING_AGG 函数