Analysis of the whole process of adding HTTPS certificate to RestTemplate

  • 2021-12-05 06:11:46
  • OfStack

Directory RestTemplate Add HTTPS Certificate Download Certificate Import JDK Generate keystore File Project Configure RestTemplate Access HTTPSmaven Configuration Verification

RestTemplate Add HTTPS Certificate

Download of certificate

First, save the unsigned certificate locally through the browser, and click Unsafe- > Certificate- > Details-- > Copy to a file and then select a file name by default, then save it. For example, I saved the certificate on the desktop and named it xx. cer

Certificate Import JDK

If you want to use the certificate in the project, you need to import the certificate into the certificate management of JDK first. The import command is as follows:

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

This command is executed in the linux server. When executing this command, open the terminal under the folder where the certificate is located, and then name the alias under 1. The alias is best and the certificate name 1. As above, it is called xx. In addition, the JDK path in the above command can be replaced by your actual path

Enter after the above command is entered, which will let you write a password, just write changeit. If changeit is not good, just write changeme 1 like chageit.

Generate an keystore file

Is it enough to just import the certificate into JDK? What I verify here is not possible, and the corresponding keystore file must be generated

keystore file generation command: keytool-import-file xx. cer-keystore xx. keystore

To do an explanation of the above command, the command is also executed under linux, of course, windows can also be executed, when the certificate is also carried out in the folder, if the prompt authority is not enough, then add sudo, windows is executed as an administrator

After entering the car, you will be asked to enter the password, so you can enter chageit accordingly

After execution, another xx. keystore file will be generated in the current path

Configuration in Project

Copy the xx. keystore file uploaded above to the classpath of your project

Copy the configuration of the following restTemplate to your project, which uses 1 httpConverter. This is to do json format conversion, and HTTPS is not too much to do, if it is not needed, it and related code can be deleted


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;
    }
}

Configuration is complete here!

RestTemplate Access HTTPS

This article briefly describes how to use restTemplate to access https under 1.

maven


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

factory of httpclient is used here

Configure


    @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;
    }

Validation


    @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);
    }

Related articles: