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;

}

目录
相关文章
|
JavaScript API
Vue3+hooks快速接入Lodop打印插件
Vue3+hooks快速接入Lodop打印插件
894 0
|
Java 程序员 Nacos
案例26-Nacos命名空间和ID不一致
Nacos命名空间和ID不一致
443 0
|
JSON fastjson Java
(fastjson)java 如何将String(字符串)与JSON互转
(fastjson)java 如何将String(字符串)与JSON互转
1485 1
|
SQL 索引
在 SQL Server 中使用 STRING_AGG 函数
【8月更文挑战第5天】
4430 2
在 SQL Server 中使用 STRING_AGG 函数
|
消息中间件 负载均衡 Kubernetes
k8s-服务(clusterIP/NodePort/LoadBanlance)
clusterIP 类型的服务 NodePort 类型的服务 LoadBanlance 类型的服务
k8s-服务(clusterIP/NodePort/LoadBanlance)
|
搜索推荐 算法
B站被删除的视频,该如何找回来?
B站被删除的视频,该如何找回来?
14287 0
|
数据库
仅当指定列列表,且SET IDENTITY_INSERT为ON时,才能对自增列赋值
仅当指定列列表,且SET IDENTITY_INSERT为ON时,才能对自增列赋值
3484 0
|
监控 安全 Java
如何保护您的SpringBoot项目:防止源代码泄露,确保更安全的部署
如何保护您的SpringBoot项目:防止源代码泄露,确保更安全的部署
4252 0
|
存储 Java 关系型数据库
springboot整合多数据源的配置以及动态切换数据源,注解切换数据源
springboot整合多数据源的配置以及动态切换数据源,注解切换数据源
3662 0
|
安全 Java Shell
"SpringBoot防窥秘籍大公开!ProGuard混淆+xjar加密,让你的代码穿上隐形斗篷,黑客也无奈!"
【8月更文挑战第11天】开发SpringBoot应用时,保护代码免遭反编译至关重要。本文介绍如何运用ProGuard和xjar强化安全性。ProGuard能混淆代码,去除未使用的部分,压缩字节码,使反编译困难。需配置ProGuard规则文件并处理jar包。xjar则进一步加密jar包内容,即使被解压也无法直接读取。结合使用这两种工具可显著提高代码安全性,有效保护商业机密及知识产权。
1925 3