欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

RestTemplate添加HTTPS证书全过程解析

程序员文章站 2022-03-23 23:29:31
目录resttemplate添加https证书证书导入jdkresttemplate访问httpsresttemplate添加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);
    }

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