java restTemplate.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java restTemplate.java相关的知识,希望对你有一定的参考价值。

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
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.SSLContexts;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;

/**
 * RestTemplate配置类
 */
@Configuration
public class RestTemplateConfig {
    private static Logger logger = LoggerFactory.getLogger ( RestTemplateConfig.class );

    @Value ("${sslContext.checkOn}")
    private String contextCheck;
    @Value("${web.upload-path}")
    private String uploadDir;

    @Bean
    public SSLContext custom() throws FileNotFoundException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = null;
        if(!Boolean.valueOf ( contextCheck)){
            logger.info ( "未开启证书检查" );
            sc = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
        }else{
            InputStream instream = null;
            KeyStore trustStore;
            try {
                File file = new File ( KeyStoreHelper.getKeyStorePath (uploadDir) );
                if(file.exists ()){
                    instream = org.apache.commons.io.FileUtils.openInputStream ( file );
                    logger.info ( "成功检测到配置的keystore文件,{}",file.getAbsolutePath () );
                }else{
                    instream = RestTemplateConfig.class.getClassLoader ().getResourceAsStream ( Constants.KEY_STORE_BASE_FILE_PATH );
                    logger.warn ( "未检测到配置的keystore文件,将使用jre自带的keystore文件代替;自定义证书将无法使用!默认jre证书库地址为:{}",Constants.KEY_STORE_BASE_FILE_PATH );
                }
                trustStore = KeyStore.getInstance ( KeyStore.getDefaultType () );
                trustStore.load ( instream, Constants.KEY_STORE_PASS.toCharArray () );
                sc = SSLContexts.custom ().loadTrustMaterial ( trustStore, new TrustSelfSignedStrategy () ).build ();
            } catch ( KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | KeyManagementException e ) {
                throw new RuntimeException ( "加载ssl的证书库文件失败",e );
            } finally {
                IOUtils.closeQuietly ( instream );
            }
        }
        return sc;
    }

    @Bean
    public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(SSLContext sslcontext) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        SSLConnectionSocketFactory ssf;
        if(!Boolean.valueOf ( contextCheck)){
            ssf = new SSLConnectionSocketFactory(sslcontext, new RestTemplateConfig.MyHostnameVerifier());
        }else {
            ssf = new SSLConnectionSocketFactory(sslcontext);
        }
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE )
                .register ( "https", ssf ).build();
        PoolingHttpClientConnectionManager result = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        result.setMaxTotal(20);
        return result;
    }

    @Bean
    public RequestConfig requestConfig() {
        RequestConfig result = RequestConfig.custom()
                .setConnectionRequestTimeout(30000)
                .setConnectTimeout(30000)
                .setSocketTimeout(30000)
                .build();
        return result;
    }

    @Bean
    public CloseableHttpClient httpClient(PoolingHttpClientConnectionManager poolingHttpClientConnectionManager, RequestConfig requestConfig) {
        CloseableHttpClient httpClient = HttpClients.custom()
//                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setConnectionManager(poolingHttpClientConnectionManager)
                .setDefaultRequestConfig(requestConfig)
                .build();
        return httpClient;
    }

    static class MyHostnameVerifier implements HostnameVerifier {
        MyHostnameVerifier() {
        }

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    @Bean
    public RestTemplate restTemplate(HttpClient httpClient) {
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        stringHttpMessageConverter.setWriteAcceptCharset(true);
        for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
            if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
                restTemplate.getMessageConverters().remove(i);
                restTemplate.getMessageConverters().add(i, stringHttpMessageConverter);
                break;
            }
        }
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new LoggingRequestInterceptor());
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
    }
}

以上是关于java restTemplate.java的主要内容,如果未能解决你的问题,请参考以下文章

Java笔记-RestTemplate(Java进程)配置代理Fiddler抓包

Java Switch

Java Math

Java 布尔运算

java [Java] Java常用代码#java

Java - 35 Java 实例