springboot集成https

1 生成秘钥

1.1 用管理员cmd 进入jdk bin 目录 C:\Program Files\Java\jdk1.8.0_301\bin

.\keytool.exe -genkeypair -alias test-https -keypass 123456 -keyalg RSA -keysize 1024 -validity 365 -keystore d:\cer2\test.keystore -storepass 123456

1.2 把生成的test.keystore文件复制到resources 目录下

2 服务端配置

server:

port: 8081

tomcat:

max-http-form-post-size: -1

ssl:

key-store: classpath:test.keystore

key-store-type: JKS

key-alias: test-https

key-store-password: 123456

key-password: 123456

3 客户端配置

把生成的test.keystore文件复制到resources 目录下

org.apache.httpcomponents

httpclient

4 restTemplate 配置

import org.apache.http.conn.ssl.NoopHostnameVerifier;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.ssl.SSLContextBuilder;

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.web.client.RestTemplate;

import javax.net.ssl.SSLContext;

@Configuration

public class RestTemplateConfiguration {

@Bean

public RestTemplate restTemplate() throws Exception {

HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();

//超时配置

factory.setReadTimeout(10000);

factory.setConnectTimeout(3000);

//https

SSLContext sslContext = SSLContextBuilder.create()

.loadTrustMaterial(new ClassPathResource("test.keystore").getFile(), "123456".toCharArray())

.build();

//连接facotry

SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

factory.setHttpClient(HttpClients.custom().setSSLSocketFactory(socketFactory).build());

return new RestTemplate(factory);

}

}

5 调用示范:

###get

public String getRequestHttps(String url) {

// 1.构建请求头

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

// 2. 执行请求

ResponseEntity exchange = restTemplateHttps.exchange(

url,

HttpMethod.GET,

new HttpEntity<>(null, headers),

new ParameterizedTypeReference() {

});

Assert.isTrue(exchange.getStatusCode().is2xxSuccessful(), "响应必须是 200 成功");

log.info("getRequest----->{}", exchange);

return exchange.getBody();

}

###post

public static String postJsonRequest(Map body, String url) {

// 1 构建请求头

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);

// 2. 执行请求

ResponseEntity exchange = restTemplateHttp.exchange(

url,

HttpMethod.POST,

new HttpEntity<>(body, headers),

new ParameterizedTypeReference() {

});

Assert.isTrue(exchange.getStatusCode().is2xxSuccessful(), "响应必须是 200 成功");

log.info("postJsonRequest----->{}", exchange);

return exchange.getBody();

}

你可能感兴趣的:(jdk,spring,boot,java,spring)