亲宝软件园·资讯

展开

RestTemplate添加HTTPS证书 RestTemplate添加HTTPS证书全过程解析

maeeki 人气:2
想了解RestTemplate添加HTTPS证书全过程解析的相关内容吗,maeeki在本文为您仔细讲解RestTemplate添加HTTPS证书的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:RestTemplate添加证书,添加HTTPS证书,RestTemplate添加HTTPS证书,下面大家一起来学习吧。

RestTemplate添加HTTPS证书

证书的下载

先通过浏览器将未签名验证的证书保存到本地, 点击 不安全–> 证书–> 详细信息 --> 复制到文件 然后默认选择 起一个文件名 , 保存即可, 比如我将证书保存在了桌面 , 命名为 xx.cer

证书导入JDK

若是想要在项目中用到证书 , 需要先将证书导入到JDK的证书管理里面, 导入命令如下:

keytool -import -noprompt -trustcacerts -alias xx -keystore /home/oracle/jdk1.8.0_181/jre/lib/security/cacerts -file xx.cer

对上面的命令做一个解释 此命令是在linux服务器内执行的 , 在执行这个命令的时候就在证书所在的文件夹下打开终端, 然后命名一下别名 , 别名最好和证书名称一致 , 如上, 都叫xx , 另外将上面命令中的JDK路径换成你的实际路径即可

上面命令输入完毕后回车 , 会让你写密码啥的 , 就写 changeit 若是changeit不行就写 changeme 一般的 chageit 就可以了

生成keystore文件

只将证书导入JDK就可以了吗? 我这里验证的是不可以的, 必须还要生成对应的 keystore文件

keystore文件生成命令: keytool -import -file xx.cer -keystore xx.keystore

对上面的命令做一个解释 , 该命令也是在linux下执行的 ,当然windows下也可以的 , 执行的时候也是在证书所在文件夹进行的 , 若是提示权限不够 那就再加sudo , windows就以管理员的身份执行

回车后又会让你输入密码 , 那么就还对应着输入 chageit 即可

执行完毕后会在当前路径下再产生一个xx.keystore文件

项目中配置

将上面上传的xx.keystore 文件文件复制到你的项目的类路径下

将下面的这个restTemplate的配置复制到你的项目中去,其中里面用到了一个httpConverter 这个是做json格式转换的, 和HTTPS没太大关系 , 若是不需要就将它以及相关代码删掉即可

package com.abc.air.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
/**
 * Created by ZhaoTengchao on 2019/4/12.
 */
@Configuration
public class RestTemplateConfig {
    @Autowired
    private FastJsonHttpMessageConverter httpMessageConverter;
    @Bean
    RestTemplate restTemplate() throws Exception {
    	HttpComponentsClientHttpRequestFactory factory = new                                                    
    	        HttpComponentsClientHttpRequestFactory();
    	    factory.setConnectionRequestTimeout(5 * 60 * 1000);
    	    factory.setConnectTimeout(5 * 60 * 1000);
    	    factory.setReadTimeout(5 * 60 * 1000);
    	    // https
    	    SSLContextBuilder builder = new SSLContextBuilder();
    	    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    	    ClassPathResource resource = new ClassPathResource("nonghang.keystore");
    	    InputStream inputStream = resource.getInputStream();
    	    keyStore.load(inputStream, null);
    	    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
    	    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
    	            .register("http", new PlainConnectionSocketFactory())
    	            .register("https", socketFactory).build();
    	    PoolingHttpClientConnectionManager phccm = new PoolingHttpClientConnectionManager(registry);
    	    phccm.setMaxTotal(200);
    	    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).setConnectionManager(phccm).setConnectionManagerShared(true).build();
    	    factory.setHttpClient(httpClient);
    	    RestTemplate restTemplate = new RestTemplate(factory);
    	    List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
            ArrayList<HttpMessageConverter<?>> convertersValid = new ArrayList<>();
            for (HttpMessageConverter<?> converter : converters) {
                if (converter instanceof MappingJackson2HttpMessageConverter ||
                    converter instanceof MappingJackson2XmlHttpMessageConverter) {
                    continue;
                }
                convertersValid.add(converter);
            }
            convertersValid.add(httpMessageConverter);
            restTemplate.setMessageConverters(convertersValid);
    	    inputStream.close();
        return restTemplate;
    }
}

到此配置完毕!

RestTemplate访问HTTPS

本文简述一下怎么使用restTemplate来访问https。

maven

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>

这里使用httpclient的factory

配置

    @Bean
    public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
    }

验证

    @Test
    public void testHttps(){
        String url = "https://free-api.heweather.com/v5/forecast?city=CN101080101&key=5c043b56de9f4371b0c7f8bee8f5b75e";
        String resp = restTemplate.getForObject(url, String.class);
        System.out.println(resp);
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论