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;

}

目录
相关文章
|
2月前
|
JSON 人工智能 前端开发
程序员在线工具箱 JSON格式化、HTTP接口调试、Mock数据、时间戳、SEO分析一站式使用
httpjson 是一个面向前端、后端、测试、运维和站长的在线开发者工具箱,提供 JSON 格式化、HTTP 在线请求、编码解码、进制转换、文本对比、行政区划查询、Mock 数据生成、AI Skills、Logo 图标尺寸转换、AI 配色、时间戳转换、网页内容读取与 SEO 分析等常用工具。无需安装,打开浏览器即可使用。
609 1
|
自然语言处理 语音技术 开发者
开源上新|FunASR多语言离线文件转写软件包
开源上新|FunASR多语言离线文件转写软件包
|
9月前
|
存储 开发者 Python
Python语言程序基本结构详解(零基础也能看懂的Python程序结构入门指南)
教程来源:https://www.vpshk.cn/教程Python程序结构清晰,包含导入模块、变量定义、函数封装和主逻辑四部分。从“Hello, World!”入门,掌握基本结构是学习Python的关键,有助于编写易读、可维护的代码,为进阶打下坚实基础。
|
存储 消息中间件 算法
操作系统常见面试题目总结,含答案
操作系统常见面试题目总结,含答案
|
SQL 索引
在 SQL Server 中使用 STRING_AGG 函数
【8月更文挑战第5天】
5040 2
在 SQL Server 中使用 STRING_AGG 函数
|
消息中间件 负载均衡 Kubernetes
k8s-服务(clusterIP/NodePort/LoadBanlance)
clusterIP 类型的服务 NodePort 类型的服务 LoadBanlance 类型的服务
k8s-服务(clusterIP/NodePort/LoadBanlance)
|
存储 搜索推荐 数据建模
阿里巴巴大数据实践之数据建模:构建企业级数据湖
阿里巴巴通过构建高效的数据湖和实施先进的数据建模策略,实现了数据驱动的业务增长。这些实践不仅提升了内部运营效率,也为客户提供了更好的服务体验。随着数据量的不断增长和技术的不断创新,阿里巴巴将持续优化其数据建模方法,以适应未来的变化和发展。
|
安全 Java Shell
"SpringBoot防窥秘籍大公开!ProGuard混淆+xjar加密,让你的代码穿上隐形斗篷,黑客也无奈!"
【8月更文挑战第11天】开发SpringBoot应用时,保护代码免遭反编译至关重要。本文介绍如何运用ProGuard和xjar强化安全性。ProGuard能混淆代码,去除未使用的部分,压缩字节码,使反编译困难。需配置ProGuard规则文件并处理jar包。xjar则进一步加密jar包内容,即使被解压也无法直接读取。结合使用这两种工具可显著提高代码安全性,有效保护商业机密及知识产权。
2251 3
|
安全 Linux 网络安全
Linux _ apache服务器部署 不同域名—访问不同网站(多网站)
Linux _ apache服务器部署 不同域名—访问不同网站(多网站)
759 1
|
数据库
仅当指定列列表,且SET IDENTITY_INSERT为ON时,才能对自增列赋值
仅当指定列列表,且SET IDENTITY_INSERT为ON时,才能对自增列赋值
4250 0

热门文章

最新文章