RestTemplate发送https请求

发布时间:2024年01月08日

一.需求描述:

调用其它系统时,发送https的post请求

二.解决思路:

在配置HttpClient时,选择忽略证书发起请求

public RestTemplate getRestTemplateByHttps(){
        // 发送请求
        try {
            CloseableHttpClient httpClient = null;
            SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build();
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
            requestFactory.setHttpClient(httpClient);
            return new RestTemplate(requestFactory);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
public JSONObject getToken(){
        Map<String, Object> map = new HashMap<>();
        map.put("acc","xxxx");
        map.put("pwd","xxxx");
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-Type", "application/json");
        // body填充
        HttpEntity<?> entity = new HttpEntity<>(map,requestHeaders);
        // 发送请求
        String url = "https://xxxxxxx/Data/StartSession";
        RestTemplate restTemplate = getRestTemplateByHttps();
        return restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody();
    }

文章来源:https://blog.csdn.net/yiye2017zhangmu/article/details/135450361
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。