java通过okhttp方式实现https请求的工具类(绕过证书验证)

目录

    • 一、引入依赖包
    • 二、okhttp方式实现的https请求工具类
      • 2.1、跳过证书配置类
      • 2.2、okhttp方式的 https工具类
    • 三、测试类

一、引入依赖包

  • 引入相关依赖包

    <!--okhttp依赖包-->
    <dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.10.0</version>
    </dependency>
    <!--lombok用于简化实体类开发-->
    <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
    </dependency>
    

二、okhttp方式实现的https请求工具类

2.1、跳过证书配置类

  • 跳过证书配置类代码

    package com.xz.https;
    import okhttp3.OkHttpClient;import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSocketFactory;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;/*** @Description 跳过证书配置类* @author xz*/
    public class OKHttpClientBuilder {public static OkHttpClient.Builder buildOKHttpClient() {try {TrustManager[] trustAllCerts = buildTrustManagers();final SSLContext sslContext = SSLContext.getInstance("SSL");sslContext.init(null, trustAllCerts, new java.security.SecureRandom());final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();OkHttpClient.Builder builder = new OkHttpClient.Builder();builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);builder.hostnameVerifier((hostname, session) -> true);return builder;} catch (NoSuchAlgorithmException | KeyManagementException e) {e.printStackTrace();return new OkHttpClient.Builder();}}private static TrustManager[] buildTrustManagers() {return new TrustManager[]{new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[]{};}}};}
    }
    

2.2、okhttp方式的 https工具类

  • okhttp方式的 https工具类代码

    package com.xz.https;import lombok.extern.slf4j.Slf4j;
    import okhttp3.*;import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;/*** @Description okhttp方式的 https工具类* @author xz*/
    @Slf4j
    public class OkhttpsUtils {/*** 获取客户端链接*/private static OkHttpClient getClient() {OkHttpClient okHttpClient = OKHttpClientBuilder.buildOKHttpClient().connectTimeout(5000, TimeUnit.SECONDS).readTimeout(20000, TimeUnit.SECONDS).writeTimeout(20000, TimeUnit.SECONDS).build();return okHttpClient;}private static Request getRequest(String url, Map<String,String> header) throws MalformedURLException {Request.Builder builder = getBuilder(header);URL uri = new URL(url);return builder.url(uri).build();}private static Request.Builder getBuilder(Map<String,String> header) {Request.Builder builder = new Request.Builder();builder.addHeader("accept", "application/json").addHeader("connection", "Keep-Alive").addHeader("Content-Type", "application/json;charset=UTF-8");if(header != null && header.entrySet().size()>0){for(Map.Entry<String,String>  entry:header.entrySet()){builder.addHeader(entry.getKey(),entry.getValue());}}return builder;}/*** doGet请求*/public static String doGet(String url, String param, Map<String,String> header) {if (param != null) {url = url + "?" + param;}String result = null;try {OkHttpClient okHttpClient = getClient();Request request = getRequest(url,header);Response response = okHttpClient.newCall(request).execute();if (response.isSuccessful()) {ResponseBody body = response.body();if (body != null) {result = body.string();} else {throw new IOException("response body is null");}} else {response.close();}} catch (IOException e) {log.error("GET请求异常,url = {}", url, e);}return result;}/*** doPost请求*/public static String doPost(String url, String param,Map<String,String> header) {OkHttpClient okHttpClient = getClient();Request.Builder builder = getBuilder(header);String result = null;try {RequestBody requestBody = RequestBody.create(param.getBytes("UTF-8"),MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE));builder.post(requestBody);Request request = builder.url(url).build();Response response = okHttpClient.newCall(request).execute();if (response.isSuccessful()) {ResponseBody body = response.body();if (body != null) {result = body.string();} else {throw new IOException("response body is null");}} else {response.close();}} catch (Exception e) {log.error("POST请求异常,url = {}", url, e);}return result;}/*** doDelete请求*/public static String doDelete(String url, String param,Map<String,String> header) {OkHttpClient okHttpClient = getClient();Request.Builder builder = getBuilder(header);String result = null;try {if (param != null) {RequestBody requestBody = RequestBody.create(param.getBytes("UTF-8"),MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE));builder.delete(requestBody);} else {builder.delete();}Request request = builder.url(url).build();Response response = okHttpClient.newCall(request).execute();if (response.isSuccessful()) {ResponseBody body = response.body();if (body != null) {result = body.string();} else {throw new IOException("response body is null");}} else {response.close();}} catch (Exception e) {log.error("DELETE请求异常,url = {}", url, e);}return result;}/*** doPut请求*/public static String doPut(String url, String param,Map<String,String> header) {OkHttpClient okHttpClient = getClient();Request.Builder builder = getBuilder(header);String result = null;try {RequestBody requestBody = RequestBody.create(param.getBytes("UTF-8"),MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE));builder.put(requestBody);Request request = builder.url(url).build();Response response = okHttpClient.newCall(request).execute();if (response.isSuccessful()) {ResponseBody body = response.body();if (body != null) {result = body.string();} else {throw new IOException("response body is null");}} else {response.close();}} catch (Exception e) {log.error("PUT请求异常,url = {}", url, e);}return result;}}

三、测试类

  • 测试代码

    package com.xz.https;import com.alibaba.fastjson.JSONObject;/*** @author: xz* @since: 2024/1/11 22:07* @description:*/
    public class HttpsUtilsTest {public static void main(String[] args) throws Exception {String url="https://xxx.com.cn:5678/gateway/user/service/getxxxx";UserReq userReq = new UserReq ();userReq .setName("张三");String result = OkhttpsUtils.doPost(url, JSONObject.toJSONString(accessTokenReq), null);System.out.println("Okhttps---https请求:"+result);}
    }
    
  • 测试输出结果

    在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/342075.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux(Centos7)安装 jenkins(jdk11+jenkins2.375),并配置JDK,Maven,Git,GitLab

安装步骤 1. JDK11安装2. Maven安装3. git安装4. Jenkins2.375安装4.1 设置中文显示4.2 端口,用户权限修改4.3 插件下载4.4 全局工具配置4.4.1 Maven配置4.4.2 JDK配置4.4.3 Git配置 4.5 系统配置4.5.1 Gitee配置 4.6 构建测试 1. JDK11安装 #下载 yum -y install fontconfig …

SpringBoot 把PageHelper分页信息返回给前端

第1步&#xff1a;定义线程容器收纳HttpHeaders和HttpStatus import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus;public class ResponseUtils {private static ThreadLocal<HttpHeaders> ThreadLocalHeaders new InheritableT…

SQL-DCL-如何用户管理,如何给用户权限?

&#x1f389;欢迎您来到我的MySQL基础复习专栏 ☆* o(≧▽≦)o *☆哈喽~我是小小恶斯法克&#x1f379; ✨博客主页&#xff1a;小小恶斯法克的博客 &#x1f388;该系列文章专栏&#xff1a;重拾MySQL &#x1f379;文章作者技术和水平很有限&#xff0c;如果文中出现错误&am…

计算机网络-2019期末考试解析

【前言】 从内容上看比较像计算机网络课程了&#xff0c;先做了。 一&#xff0e;填空选择题&#xff08;共 20 分&#xff0c;每空 1 分&#xff09; 1 、双绞线由两根相互绝缘的、绞合成均匀的螺纹状的导线组成&#xff0c;下列关于双绞线的叙述&#xff0c;不正确的是___ __…

多端多用户万能DIY商城系统源码:自营+多商户入驻商城系统 独立部署 带完整的安装代码包以及搭建教程

电子商务行业日新月异&#xff0c;许多企业希望能够通过线上商城拓展业务。但是&#xff0c;传统商城系统往往无法满足多样化、个性化的需求&#xff0c;而且开发周期长、成本高。罗峰就来给大家分享一款多端多用户万能DIY商城系统源码&#xff0c;搭建简单。 以下是部分代码示…

win系统搭建Minecraft世界服务器,MC开服教程,小白开服教程

Windows系统搭建我的世界世界服务器&#xff0c;Minecraft开服教程&#xff0c;小白开服教程&#xff0c;MC 1.19.4版本服务器搭建教程。 此教程使用 Mohist 1.19.4 服务端&#xff0c;此服务端支持Forge模组和Bukkit/Spigot/Paper插件&#xff0c;如果需要开其他服务端也可参…

【Node.js学习 day4——模块化】

模块化介绍 什么是模块化与模块&#xff1f; 将一个复杂的程序文件依据一定规则&#xff08;规范&#xff09;拆分成多个文件的过程称之为模块化 其中拆分的每个文件就是一个模块&#xff0c;模块的内部数据是私有的&#xff0c;不过模块可以暴露内部数据以便其他模块使用。什…

网上的大流量卡,这几点不注意你就申请不到了

网上的大流量卡月租低&#xff0c;流量多&#xff0c;相对于手机套餐每个月我们可以省下不少的费用&#xff0c;但是&#xff0c;流量卡便宜归便宜&#xff0c;也并不是随便申请的&#xff0c;以下这几种情况大家先自查一下&#xff0c;有的话&#xff0c;建议你不要申请了&…

机器学习-线性回归

1、线性回归解决的问题 线性回归是利用被称为线性回归方程的最小平方函数对一个或者多个自变量和因变量之间关系进行建模的一种回归分析。这种函数是一个或者多个被称为回归系数的模型参数的线性组合。 2、一元线性回归 一元线性回归分析&#xff1a;找到一条直线能够最大程…

(Arcgis)matlab编程批量处理hdf4格式转换为tif格式

国家青藏高原科学数据中心 中国区域1km无缝地表温度数据集&#xff08;2002-2020&#xff09; 此代码仅用于该数据集处理 版本&#xff1a;arcgis10.2 matlab2020 参考&#xff1a;MATLAB hdf(h5)文件转成tif图片格式&#xff08;批量处理&#xff09; 此代码仅用于该数据集处…

算法的复杂度分析

[王有志](https://www.yuque.com/wangyouzhi-u3woi/dfhnl0/hqrch62un0cc9sp2?singleDoc# 《&#x1f525;快来关注我》)&#xff0c;一个分享硬核Java技术的互金摸鱼侠加入Java人的提桶跑路群&#xff1a;[共同富裕的Java人](https://www.yuque.com/wangyouzhi-u3woi/dfhnl0/n…

PostgreSQL 16 的新功能:双向逻辑复制

介绍 在这篇博客中&#xff0c;我们将讨论 Postgres 16 中新增的一些更高级的特性。假设您拥有一些 Linux、Postgres 和 SQL 的经验&#xff0c;因为我们不仅要讨论这些新功能&#xff0c;还要讨论如何实现它们。本博客是使用在 Ubuntu 23.04 上运行的 PostgreSQL 16&#xff…