美文网首页
springboot restTemplate https请求

springboot restTemplate https请求

作者: 万事俱备就差一个程序员了 | 来源:发表于2021-09-23 19:12 被阅读0次

配置文件RestTemplateConfig

importorg.apache.http.conn.ssl.NoopHostnameVerifier;importorg.apache.http.conn.ssl.SSLConnectionSocketFactory;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClientBuilder;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.ssl.SSLContexts;importorg.apache.http.ssl.TrustStrategy;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.http.client.ClientHttpRequestFactory;importorg.springframework.http.client.HttpComponentsClientHttpRequestFactory;importorg.springframework.web.client.RestTemplate;importjavax.net.ssl.SSLContext;importjava.security.KeyManagementException;importjava.security.KeyStoreException;importjava.security.NoSuchAlgorithmException;@ConfigurationpublicclassRestTemplateConfig{@BeanpublicRestTemplaterestTemplate(ClientHttpRequestFactoryfactory){returnnewRestTemplate(factory);}@BeanpublicClientHttpRequestFactorysimpleClientHttpRequestFactory(){HttpComponentsClientHttpRequestFactoryfactory=newHttpComponentsClientHttpRequestFactory();factory.setConnectTimeout(15000);factory.setReadTimeout(5000);returnfactory;}publicstaticHttpComponentsClientHttpRequestFactorygenerateHttpRequestFactory()throwsNoSuchAlgorithmException,KeyManagementException,KeyStoreException{TrustStrategyacceptingTrustStrategy=(x509Certificates,authType)->true;SSLContextsslContext=SSLContexts.custom().loadTrustMaterial(null,acceptingTrustStrategy).build();SSLConnectionSocketFactoryconnectionSocketFactory=newSSLConnectionSocketFactory(sslContext,newNoopHostnameVerifier());HttpClientBuilderhttpClientBuilder=HttpClients.custom();httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);CloseableHttpClienthttpClient=httpClientBuilder.build();HttpComponentsClientHttpRequestFactoryfactory=newHttpComponentsClientHttpRequestFactory();factory.setHttpClient(httpClient);returnfactory;}}

发起请求

与http请求不同的是,https使用restTemplate的时候需要手动创建对象,并传入参数。而http直接用Autowired注入restTemplate对象就可以直接使用。

Stringurl="https://xxxx";RestTemplaterestTemplateHttps=newRestTemplate(RestTemplateConfig.generateHttpRequestFactory());ResponseEntity<String>results=restTemplateHttps.exchange(url,HttpMethod.GET,entity(),String.class);JSONObjectjson=JSON.parseObject(results.getBody());System.out.println(json);

4人点赞

spring boot

作者:一叶舟遥

链接:https://www.jianshu.com/p/9849ff94f07a

来源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

相关文章

网友评论

      本文标题:springboot restTemplate https请求

      本文链接:https://www.haomeiwen.com/subject/tovogltx.html