httpUtils

package coo.huawei.Knowledge.http_;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import coo.huawei.Knowledge.restTemplateUtil_.SSLOption;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
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.DefaultConnectionKeepAliveStrategy;

import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;

import static coo.huawei.Knowledge.restTemplateUtil_.SSLManager.createSSLContext;

@Slf4j
public class HttpsUtil  {

    private static final String[] SUPPORTED_PROTOCOLS = new String[] {"TLSv1.2"};
    private static final String[] SUPPORTED_CIPHER_SUITES = new String[] {
            "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
    };

    @Resource
    private Environment environment;

    public <T> String post(T data) {
        try (CloseableHttpClient httpClient = createHttpsClient()) {
            HttpComponentsClientHttpRequestFactory cHttpReqFactory = new HttpComponentsClientHttpRequestFactory(
                    httpClient);
            RestTemplate restTemplate = new RestTemplate(cHttpReqFactory);
            HttpHeaders headers = new HttpHeaders();
            headers.add("connection", "Keep-Alive");
            headers.add("accept", "*/*");
            headers.add("Content-Type", "application/json");
            headers.add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            HttpEntity<T> entity = new HttpEntity<>(data, headers);
            ResponseEntity<String> exchange = restTemplate.exchange("url", HttpMethod.POST, entity,
                    String.class);
            return exchange.getBody();
        } catch (Exception e) {
            log.error("post Exception ", e);
        }
        return StringUtils.EMPTY;
    }

    private CloseableHttpClient createHttpsClient() throws Exception {
        SSLConnectionSocketFactory scsf = getSSLConnectionSocketFactory();
        RequestConfig defaultConfig = RequestConfig.custom()
                .setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .setExpectContinueEnabled(true)
                .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
                .setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
                .setConnectTimeout(30000)
                .build();
        org.apache.http.config.Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", scsf)
                .build();
        PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(sfr);
// 默认请求验证
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        headers.add(new BasicHeader("Authorization", "xxxxxxxxx")); //进行用户身份验证
        return HttpClients.custom()
                .setConnectionManager(pcm)
                .setDefaultRequestConfig(defaultConfig)
                .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                .setDefaultHeaders(headers)
                .build();
    }

    private SSLConnectionSocketFactory getSSLConnectionSocketFactory() throws Exception {
        SSLOption sslOption = getSslOption();
        SSLContext sslContext = createSSLContext(sslOption);
        String[] supportedProtocols = sslOption.getSupportedProtocols();
        if (supportedProtocols == null || supportedProtocols.length == 0) {
            supportedProtocols = SUPPORTED_PROTOCOLS;
        }
        String[] supportedCipherSuites = sslOption.getSupportedCipherSuites();
        if (supportedCipherSuites == null || supportedCipherSuites.length == 0) {
            supportedCipherSuites = SUPPORTED_CIPHER_SUITES;
        }
        return new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites,
                NoopHostnameVerifier.INSTANCE);
    }

    private SSLOption getSslOption() {
        PropertyMapper map = PropertyMapper.get();
        SSLOption sslOption = new SSLOption();
        try {
            String keyStore = ResourceUtils.getFile(
                    Objects.requireNonNull(environment.getProperty("xxx.xxx.xxx"))).getCanonicalPath();
            map.from(keyStore).whenNonNull().to(sslOption::setKeyStorePath);
            String trustStore = ResourceUtils.getFile(
                    Objects.requireNonNull(environment.getProperty("xxx.xxx.xxx"))).getCanonicalPath();
            map.from(trustStore).whenNonNull().to(sslOption::setTrustStorePath);
        } catch (Exception e) {
            log.error("set keyStore and trustStore error");
        }
        map.from(environment.getProperty("xxx.xxx.xxx"))
                .whenNonNull()
                .to(sslOption::setKeyStorePassword);
        map.from(environment.getProperty("xxx.xxx.xxx")).whenNonNull().to(sslOption::setKeyStoreType);
        map.from(environment.getProperty("xxx.xxx.xxx"))
                .whenNonNull()
                .to(sslOption::setTrustStorePassword);
        map.from(environment.getProperty("xxx.xxx.xxx")).whenNonNull().to(sslOption::setTrustStoreType);
        return sslOption;
    }
}

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值