HTTP工具

简介: 本文介绍了Java中通过HttpClient发送HTTP/HTTPS的GET和POST请求,并在请求头中添加AppKey和Secret的方法,包含设置超时参数、SSL安全连接及资源释放的完整实现,适用于安全通信场景。

HTTP-GET带header请求HTTP-POST带header请求HTTPS-POST带header请求

Java

运行代码复制代码

//设置链接超时和请求超时等参数,否则会长期停止或者崩溃

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;

}





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;

}



相关文章
|
传感器 数据采集 运维
常见的中断源类型详解
【4月更文挑战第4天】常见的中断源类型详解
1531 3
|
2月前
|
人工智能 机器人 Java
黑马最新项目
AIGC项目涵盖大模型私有化部署、聊天机器人、RAG知识库及代码提示工具;天机AI集成SpringAI与多模型工作流;云岚到家聚焦微服务与分布式架构;四方保险构建统一支付与时序数据应用;星辰WMS与Dify项目即将发布。
109 0
黑马最新项目
|
2月前
|
canal 缓存 关系型数据库
微服务原理篇(Canal-Redis)
本文介绍了ES索引同步的常见方案,重点讲解Canal+MQ数据同步机制。通过解析MySQL的binlog日志,Canal模拟slave伪装接入主库,实现增量数据捕获,并结合RabbitMQ保证消息顺序性地同步至Elasticsearch。同时探讨了缓存一致性问题,提出使用分布式锁(如Redis)控制并发写操作,避免双写不一致。还涵盖Redis持久化、集群模式、过期淘汰策略及缓存三剑客(穿透、雪崩、击穿)的解决方案,系统梳理了高并发场景下的数据同步与缓存保障技术体系。
88 0
 微服务原理篇(Canal-Redis)
|
2月前
|
Arthas 存储 运维
记Arthas实现一次CPU排查与代码热更新
本文介绍使用Arthas排查Java应用CPU占用过高问题的完整流程,涵盖线程分析、阻塞定位、watch命令追踪异常、jad反编译实现热更新及火焰图分析,实现无需重启应用的高效故障排查与代码修复。
91 0
|
2月前
|
机器学习/深度学习 人工智能 自然语言处理
大模型专业名词解释手册
本手册由油炸小波设计提示词、Manus创作,系统梳理大语言模型核心概念,涵盖基础原理、训练技术、优化压缩、推理应用、评估调试及伦理安全六大模块,深入浅出解析LLM关键技术术语。
292 0
|
3月前
|
弹性计算
阿里云u1云服务器通用算力型ECS收费标准及性能参数表:一年、1小时和一个月收费价格
阿里云ECS通用算力型u1实例,搭载Intel Xeon Platinum处理器,是企业入门级云服务器。现推2核4G、5M带宽、80G硬盘配置,限时优惠价199元/年,新老用户同享。提供按量付费及多种包期选择,性价比高,适用于网站、应用托管等场景。
463 0
|
SQL 存储 自然语言处理
StoreView SQL,让数据分析不受地域限制
日志服务SLS是云原生观测与分析平台,支持Log、Metric、Trace等数据的大规模、低成本实时处理。为解决跨地域数据联合分析问题,SLS推出StoreView功能,可将多地域、多项目的Logstore组合成虚拟Logstore,简化查询分析流程。相比传统ETL方式,StoreView无需同步数据,减少存储成本和延迟,同时支持数据可见性控制、查询式ETL处理及异构数据Schema对齐等功能,提升跨域数据分析效率。通过__project__和__logstore__两个Meta字段,用户还能识别数据来源,实现精细化分析。
318 21
|
7月前
|
SQL Java 关系型数据库
如何系统学习Java:从零基础到项目实战的完整指南
本指南为Java系统化学习路线,涵盖从基础语法到项目实战的全过程。分为四大阶段:Java基础、核心技术、数据库与框架、项目实战,结合学习资源与实践策略,助你高效掌握编程技能,迈向Java工程师之路。
468 0
|
12月前
|
存储 Kubernetes 测试技术
企业级LLM推理部署新范式:基于ACK的DeepSeek蒸馏模型生产环境落地指南
企业级LLM推理部署新范式:基于ACK的DeepSeek蒸馏模型生产环境落地指南
671 12