zoukankan      html  css  js  c++  java
  • 使用restTemplate来访问https

    1、maven: <dependency>

            <groupId>org.apache.httpcomponents</groupId>

            <artifactId>httpclient</artifactId>

            <version>4.5.3</version>

          </dependency>

    2、@Configuration
    public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
    .loadTrustMaterial(null, acceptingTrustStrategy)
    .build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom()
    .setSSLSocketFactory(csf)
    .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
    new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    return restTemplate;
    }
    }

    测试:

    public String getData()
    {
    //接口地址
    String url = "https://free-api.heweather.com/v5/forecast?city=CN101080101&key=5c043b56de9f4371b0c7f8bee8f5b75e";
    Map<String, Object> params = new HashMap<>();
    params.put("start_time", "20180824");
    params.put("end_time", "20180827");
    // RestTemplate restTemplate = new RestTemplate();//此处直接autowire即可,不用new
    HttpEntity httpEntity = new HttpEntity(params, null);
    ResponseEntity<String> request = restTemplate.postForEntity(url, httpEntity, String.class);
    return request.getBody().toString();
    }

  • 相关阅读:
    Win32 键盘事件
    好用的Markdown 编辑器及工具
    如何激发您孩子的学习动力和兴趣
    横扫芯片后,紫光欲进军公有云 数百亿资金已到位(大事表)
    C#更改控制台文本颜色
    I/O多路复用
    Python 安装 httpie
    Elasticsearch 5.0
    认证架构
    注册微信小程序
  • 原文地址:https://www.cnblogs.com/yuxifly828/p/9857521.html
Copyright © 2011-2022 走看看