RestTemplate发送https请求

一.需求描述:

调用其它系统时,发送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 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,java,网络协议)