import com.alibaba.fastjson.JSONObject; 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.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Component; import org.springframework.util.DigestUtils; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext; import java.io.UnsupportedEncodingException;
@Component public class RestTemplateConfig { @Bean("restTemplate") public RestTemplate restTemplate() { try{ RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory()); return restTemplate; }catch (Exception e){ logger.error(e.getMessage()); throw new RuntimeException("unSSLRestTemplate bean创建失败,原因为:" + e.getMessage()); } }
private static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory() throws Exception{ TrustStrategy acceptingTrustStrategy = ((x509Certificates, authType) -> true); SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setSSLSocketFactory(connectionSocketFactory); CloseableHttpClient httpClient = httpClientBuilder.build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setHttpClient(httpClient); return factory; }
}