RestTemplate是Spring提供的用于访问Rest服务的客户端,提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。RestTemplate 默认使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接(SimpleClientHttpRequestFactory),不需要配置证书信息,但如果调用https请求时的证书不合法,会报”unable to find valid certification path to requested target“错误。这时可以使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务来配置证书。

代码如下:

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; @Component("httpClientFactory")
public class HttpClientFactory { @Value("${restclient.readTimeout}")
private int readTimeout; @Value("${restclient.connectTimeout}")
private int connectTimeout; public CloseableHttpClient acceptsUntrustedCertsHttpClient() throws NoSuchAlgorithmException,
KeyManagementException, KeyStoreException {
SSLContext sslcontext = SSLContexts.custom().setSecureRandom(new SecureRandom())
.loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
.setConnectTimeout(connectTimeout).setStaleConnectionCheckEnabled(true).build(); return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(defaultRequestConfig).build();
}
}

初始化httpClient

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="httpClient" factory-bean="httpClientFactory" factory-method="acceptsUntrustedCertsHttpClient" /> <bean id="clientHttpRequestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<constructor-arg ref="httpClient" />
</bean> <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg index="0">
<list>
<bean id="byteArrayHttpMessageConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"></constructor-arg>
</bean>
<bean id="resourceHttpMessageConverter" class="org.springframework.http.converter.ResourceHttpMessageConverter"></bean>
<bean id="sourceHttpMessageConverter" class="org.springframework.http.converter.xml.SourceHttpMessageConverter"></bean>
<bean id="allEncompassingFormHttpMessageConverter" class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"></bean>
</list>
</constructor-arg>
<property name="requestFactory" ref="clientHttpRequestFactory" />
</bean>
</beans>

配置resttemplate

RestTemplate请求https忽略证书认证的更多相关文章

  1. svnkit https 忽略证书认证

    直接上代码 解决jdk版本问题:Security.setProperty("jdk.tls.disabledAlgorithms", ""); import j ...

  2. java实现https免证书认证

    java实现https免证书认证   解决方法: 1.下载两个包,httpclient-4.2.jar和httpcore-4.2.jar,复制以下代码就可使用. 2.调用类代码: String htt ...

  3. SSL通信-忽略证书认证错误

    .NET的SSL通信过程中,使用的证书可能存在各种问题,某种情况下可以忽略证书的错误继续访问.可以用下面的方式跳过服务器证书验证,完成正常通信. 1.设置回调属性ServicePointManager ...

  4. https绕过证书认证请求 Get或Post请求(证书过期,忽略证书)

    报错信息 解决: postman方式 java请求 报错信息 javax.net.ssl.SSLHandshakeException: sun.security.validator.Validator ...

  5. java https post请求并忽略证书,参数放在body中

    1 新建java类,作用是绕过证书用 package cn.smartercampus.core.util; import java.security.cert.CertificateExceptio ...

  6. https的证书认证 iOS版

    一.证书链 SecTrustRef: SecTrustRef trust = challenge.protectionSpace.serverTrust; 需要先拿出一个 SecTrustRef 对象 ...

  7. Https 忽略证书\使用自定义证书的java代码实现

    public SSLContext createIgnoreVerifySSL() throws KeyManagementException, NoSuchAlgorithmException, K ...

  8. 各种编程语言忽略http的SSL证书认证

    目录 前言 代码 go语言 Python语言 Ruby语言 Java语言 PHP语言 C#语言 前言 我们内部测试的http服务器很多时候证书都是没有经过第三方认证的,我们发送http请求基本上都是忽 ...

  9. HTTP-java访问https资源时,忽略证书信任问题,代码栗子

    java程序在访问https资源时,出现报错 sun.security.validator.ValidatorException: PKIX path building failed: sun.sec ...

随机推荐

  1. doxygen的简单使用(快速上手)

    在网上找了很久一个简单的doxygen教程,这个是最简单的,让你看完之后马上就能写doxygen格式的代码 doxygen是一种从源代码生成文档的工具,支持多种语言.当然,源代码中需按一定的格式写注释 ...

  2. 用hashlib生成动态token

    生成token: import timeimport hashlib token ='jdhfvasuiodfbhsjdbvaio' client_time = time.time() client_ ...

  3. mysql 约束条件 auto_increment 自动增长 清空表 自动增长情况

    清空表情况: mysql> delete from t20; Query OK, rows affected (0.00 sec) mysql> show create table t20 ...

  4. docker镜像上传到阿里云

    目前上传本地镜像到网上有多种途径,一个是上传到hub上,一个是阿里云镜像仓库,还要其他服务器. 上传到hub上实在是太慢了,我的服务器用的是阿里云,所以选择上传到阿里云镜像仓库中. 前提条件:linu ...

  5. labview 的连接

    https://www.youtube.com/watch?v=AsQ56CmnfEA&list=PLp02wZHiCj4tcot7tPumcOeVR51oqzf6V

  6. mysql数据库优化的几种方法

    1.选取最适用的字段属性 MySQL可以很好的支持大数据量的存取,但是一般说来,数据库中的表越小,在它上面执行的查询也就会越快.因此,在创建表的时候,为了获得更好的性能,我们可以将表中字段的宽度设得尽 ...

  7. 下一个亿万市场:企业级SaaS服务谁能独领风骚

    注:SaaS是Software-as-a-Service(软件即服务)的简称,一种完全创新的软件应用模式,简单来说SaaS即为提供商基于互联网为企业提供软件服务. ​对中小型企业来说:SaaS是采用先 ...

  8. ubuntu apt-get 安装 lnmp

    最近在 Ubuntu 14.04 LTS 安装 LNMP 一键安装包的时候出现了问题,PHP 5 服务没有启动,只好使用 Ubuntu 官方源进行安装: Nginx (读音 “engine x”)免费 ...

  9. 一道仅有7人通过的超5星微软比赛题目-------解题思路&优秀代码分享,邀你来“找茬儿”

    6月23日英雄会平台发布了一道难度为超5星的微软比赛题目,截止活动结束共有300多名编程爱好者参与线上答题,而最终通过者仅有7人,通过率仅为2%.为什么成绩如此出人意料?是因为题目的英文描述难以理解? ...

  10. Rsync结合Inotify 实时同步配置(更新之前繁琐的传输认证)

    今天一位CU的友友根据之前介绍过 通过rsync+inotify-tools+ssh实现触发式远程实时同步  配置分发系统,但是由于认证繁琐,很容易出错,我今天重新整理了下,用rsync密码文件pas ...