通常如果rest服务支持https,需申请收费的ssl证书,但也可自制这种证书。
httpClient进行链接时要进行相应的设置, 主要是设置SSLContext中的
TrustSelfSignedStrategy:
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import org.apache.http.client.config.RequestConfig;
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.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HttpClientConfiguration {
@Bean
public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(AbstractProperties kycProperties) {
PoolingHttpClientConnectionManager result =
new PoolingHttpClientConnectionManager(
kycProperties.getHttpConnectionTimeToLiveMinu(),
TimeUnit.MINUTES
);
result.setMaxTotal(200);
result.setDefaultMaxPerRoute(20);
return result;
}
@Bean
public RequestConfig requestConfig(AbstractProperties kycProperties) {
return RequestConfig
.custom()
.setConnectionRequestTimeout(kycProperties.getHttpConnectionTimeout())
.setConnectTimeout(kycProperties.getHttpConnectionTimeout())
.setSocketTimeout(kycProperties.getHttpConnectionTimeout())
.build();
}
@Bean
public SSLContext sslContext() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
return SSLContexts
.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build()
;
}
@Bean
public CloseableHttpClient httpClient(AbstractProperties kycProperties) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
return HttpClients
.custom()
// .setConnectionManager(poolingHttpClientConnectionManager(null))
.setDefaultRequestConfig(requestConfig(null))
.setKeepAliveStrategy(
new MyConnectionKeepAliveStrategy(
kycProperties.getHttpConnectionTimeToLiveMinu(),
TimeUnit.MINUTES
)
)
.setMaxConnTotal(200)
.setMaxConnPerRoute(20)
// .setConnectionTimeToLive(
// kycProperties.getHttpConnectionTimeToLiveMinu(),
// TimeUnit.MINUTES
// )
.setSSLContext(sslContext())
.build();
}
}
相应设置
http-connection-timeout: 30000
http-connection-time-to-live-minu: 5