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;

}



相关文章
|
11月前
|
canal 缓存 关系型数据库
微服务原理篇(Canal-Redis)
本文介绍了ES索引同步的常见方案,重点讲解Canal+MQ数据同步机制。通过解析MySQL的binlog日志,Canal模拟slave伪装接入主库,实现增量数据捕获,并结合RabbitMQ保证消息顺序性地同步至Elasticsearch。同时探讨了缓存一致性问题,提出使用分布式锁(如Redis)控制并发写操作,避免双写不一致。还涵盖Redis持久化、集群模式、过期淘汰策略及缓存三剑客(穿透、雪崩、击穿)的解决方案,系统梳理了高并发场景下的数据同步与缓存保障技术体系。
1171 0
 微服务原理篇(Canal-Redis)
|
11月前
|
人工智能 机器人 Java
黑马最新项目
AIGC项目涵盖大模型私有化部署、聊天机器人、RAG知识库及代码提示工具;天机AI集成SpringAI与多模型工作流;云岚到家聚焦微服务与分布式架构;四方保险构建统一支付与时序数据应用;星辰WMS与Dify项目即将发布。
579 0
黑马最新项目
|
8月前
|
JSON API 数据安全/隐私保护
大模型应用:大模型的本地 API 服务:FastAPI 封装与接口鉴权.44
本文详解本地大模型API的接口发布与鉴权调试,重点介绍Postman工具实操。涵盖FastAPI封装原理、API Key与极简JWT两种鉴权方式,深入解析JWT结构(Header/Payload/Signature)、无状态验证、过期机制及完整调用流程,助开发者安全、高效调试本地大模型服务。
1230 7
|
11月前
|
缓存
QLExpress使用及源码分析
本文介绍基于QLExpress的规则引擎实现方案,涵盖实体构建、接口定义与脚本编写。通过@QLAlias注解映射字段别名,结合YAML配置规则表达式,实现逻辑解耦。运行时动态解析AST语法树,支持汉化变量与上下文绑定,并提供缓存与延迟执行机制,提升性能与灵活性。
219 0
QLExpress使用及源码分析
|
11月前
|
存储 关系型数据库 MySQL
微服务原理篇(XXLJOB-幂等-MySQL)
本文介绍了XXL-JOB任务调度的优势、组成结构及热点商品缓存更新任务的实现,涵盖幂等性概念与解决方案,并深入解析了MySQL存储引擎特性、索引失效场景、回表与覆盖索引原理以及SQL调优和分库分表策略。
444 0
微服务原理篇(XXLJOB-幂等-MySQL)
|
11月前
|
缓存 Dubbo Java
什么是API网关
API网关是一种统一接收外部请求并转发至后端服务的中间层,具备请求路由、协议转换、鉴权、限流、熔断降级等功能。它简化了客户端与多个微服务之间的交互,提升了系统安全性与可维护性,常见实现有Kong、SOUL、Zuul等。
272 0
|
11月前
|
Arthas 存储 运维
记Arthas实现一次CPU排查与代码热更新
本文介绍使用Arthas排查Java应用CPU占用过高问题的完整流程,涵盖线程分析、阻塞定位、watch命令追踪异常、jad反编译实现热更新及火焰图分析,实现无需重启应用的高效故障排查与代码修复。
348 0
|
11月前
|
人工智能 自然语言处理 API
全面认识MCP:大模型连接真实世界的“USB-C接口”
MCP(模型上下文协议)是Anthropic推出的开放标准,被誉为AI时代的“USB-C”。它统一了大模型与工具、数据源的连接方式,简化集成,提升安全与扩展性,推动AI智能体实现复杂任务自动化,正重塑全球AI应用生态。
1624 0
|
11月前
|
XML 算法 安全
详解RAG五种分块策略,技术原理、优劣对比与场景选型之道
RAG通过检索与生成结合,提升大模型在企业场景的准确性与可控性。分块策略是其核心,直接影响检索效果与生成质量。本文系统解析五种主流分块方法:固定大小、语义、递归、基于结构及LLM分块,对比其优缺点与适用场景,并提出组合优化建议,助力构建高效、可信的RAG系统。
468 0
|
11月前
|
机器学习/深度学习 人工智能 自然语言处理
大模型专业名词解释手册
本手册由油炸小波设计提示词、Manus创作,系统梳理大语言模型核心概念,涵盖基础原理、训练技术、优化压缩、推理应用、评估调试及伦理安全六大模块,深入浅出解析LLM关键技术术语。
840 0