RestTemplate HTTPS请求忽略SSL证书

news/2024/7/7 20:20:52

问题描述

使用RestTemplate发送HTTPS请求的时候,出现了这样的一个问题:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

RestTemplate 默认不支持https协议

解决方案:

        第一种是忽略认证

        第二种是导入证书,比较复杂(比第一种安全) 


解决方案:

这里说一下第一种解决方案,忽略认证

RestTemplateConfig

package com.test.config;

import java.nio.charset.Charset;
import java.util.List;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig{
	@Bean("restTemplate")
	public RestTemplate RestTemplate() {
		HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
		httpRequestFactory.setConnectionRequestTimeout(30000);
		httpRequestFactory.setConnectTimeout(30000);
		httpRequestFactory.setReadTimeout(30000);
		return new RestTemplate(httpRequestFactory);
	}
	
	/**
	 * 用于https请求,忽略认证
	 * @return	unSSLRestTemplate
	 */
	@Bean("unSSLRestTemplate")
	public RestTemplate restTemplateHttps()  {
        RestTemplate restTemplate = null;
        try {
            TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

            HttpClientBuilder clientBuilder = HttpClients.custom();

            CloseableHttpClient httpClient = clientBuilder.setSSLSocketFactory(sslsf).build();

            HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
            httpRequestFactory.setConnectionRequestTimeout(30000);
            httpRequestFactory.setConnectTimeout(30000);
            httpRequestFactory.setReadTimeout(30000);
    		
            httpRequestFactory.setHttpClient(httpClient);

            restTemplate = new RestTemplate(httpRequestFactory);
            //解决乱码
            List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
            httpMessageConverters.stream().forEach(httpMessageConverter ->{
            	if(httpMessageConverter instanceof StringHttpMessageConverter){
            		StringHttpMessageConverter messageConverter = (StringHttpMessageConverter)httpMessageConverter;
            		messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
            	}
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return restTemplate;
    }
}

测试代码

package com.test.service;

import javax.annotation.Resource;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * http请求&https请求
 */
@Service
public class TestService {
	//http请求
	@Resource(name = "restTemplate")
    private RestTemplate restTemplate;
	//https请求
	@Resource(name = "unSSLRestTemplate")
    private RestTemplate unSSLRestTemplate;

	/**
	 * http请求
	 */
    public void interfaceHttp(JSONObject params) {
		//参数
		String json = params.toJSONString();
		//请求头
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
	
		HttpEntity<String> formEntity = new HttpEntity<String>(json, headers);
		
		restTemplate.postForObject(URL, formEntity, String.class);
    }
	
	/**
	 * https请求
	 */
    public void interfaceHttps(JSONObject params) {
		//参数
		String json = params.toJSONString();
		//请求头
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
	
		HttpEntity<String> formEntity = new HttpEntity<String>(json, headers);
		
		unSSLRestTemplate.postForObject(URL, formEntity, String.class);
    }
}

说明:这里兼容http和https请求,只需要指定名称即可 

 


http://lihuaxi.xjx100.cn/news/1429326.html

相关文章

Endnote插入生成参考文献的四种方式

Endnote插入生成参考文献的四种方式 为了熟练Endnote进行在word中插入参考文献&#xff0c;本文介绍四种插入生成参考文献的四种方式。 一、采用Endnote插入按钮方式生成 word选中插入参考文献位置—转入endnote—选中要插入的文献—点击Endnote插入按钮&#xff0c;过程如图…

Android Studio实现Spinner下拉列表

效果图 点击下拉列表 点击某一个下拉列表 MainActivity package com.example.spinneradapterpro;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Spinn…

VGGNet剪枝实战:使用VGGNet训练、稀疏训练、剪枝、微调等,剪枝出只有3M的模型(二)

文章目录 稀疏训练VGGNet剪枝导入库文件测试函数定义全局参数BN通道排序制作Mask剪枝操作 微调微调方法微调结果 稀疏训练VGGNet 新建train_sp.py脚本。稀疏化训练的过程和正常训练类似&#xff0c;不同的是在BN层中各权重加入稀疏因子&#xff0c;代码如下&#xff1a; def …

Mysql报错1194 - Table ‘‘ is marked as crashed and should be repaired的解决办法

本篇文章主要讲解&#xff1a;Mysql报错1194 - Table ‘’ is marked as crashed and should be repaired的解决办法。 日期&#xff1a;2023年8月9日 作者&#xff1a;任聪聪 具体现象 说明&#xff1a;执行sql语句查询或者检索相关数据时会出现如下报错内容&#xff1a; 11…

CSV文件编辑器——Modern CSV for mac

Modern CSV for Mac是一款功能强大、操作简单的CSV文件编辑器&#xff0c;适用于Mac用户快速、高效地处理和管理CSV文件。Modern CSV具有直观的用户界面&#xff0c;可以轻松导入、编辑和导出CSV文件。它支持各种功能&#xff0c;包括排序、过滤、查找和替换&#xff0c;使您能…

Qt事件过滤器

1 介绍 事件过滤器是一种机制&#xff0c;当某个QObject没有所需要的事件功能时&#xff0c;可将其委托给其它QObject&#xff0c;通过eventFilter成员函数来过滤实现功能。 2 主要构成 委托&#xff1a; ui->QObject1->installEventFilter(QObject2); eventFilter声明 …

NLP(六十五)LangChain中的重连(retry)机制

关于LangChain入门&#xff0c;读者可参考文章NLP&#xff08;五十六&#xff09;LangChain入门 。   本文将会介绍LangChain中的重连机制&#xff0c;并尝试给出定制化重连方案。   本文以LangChain中的对话功能&#xff08;ChatOpenAI&#xff09;为例。 LangChain中的重…

/proc directory in linux

Its zero-length files are neither binary nor text, yet you can examine and display themUnder Linux, everything is managed as a file; even devices are accessed as files (in the /dev directory). Although you might think that “normal” files are either text …