RestTemplate初识

发送GET请求:

//设置请求头
HttpHeaders headers = new HttpHeaders(); headers.add("token",PostUtils.getToken()); //调用接口所需token,如果项目中没加权限拦截可以不需要这个token设置
//请求体 HttpEntity
<String> requestEntity = new HttpEntity<>(null, headers);
//发起请求 RestTemplate restTemplate
=new RestTemplate(); ResponseEntity<JSONObject> jsonObjectResponseEntity = restTemplate.exchange("调用的接口地址", HttpMethod.GET, requestEntity,JSONObject.class);
//将拿到的数据转换成自己想要的格式 ResponseLockList responseLockList
=JSON.parseObject(jsonObjectResponseEntity.getBody().toString(), new TypeReference<ResponseLockList>() {}); 

发送POST请求:

//入参
JSONObject jsonObj=null;
//设置请求头
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); //请求的入参方式是json headers.add("token", getToken()); //调用接口所需token,如果项目中没有权限拦截可以不需要这个token设置
//请求体 HttpEntity
<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
//发送请求 RestTemplate restTemplate
= new RestTemplate();
//返回的json字符串 String json
=restTemplate.postForObject("调用的接口地址", formEntity, String.class);
//将json字符串转换成对象 ResponseSaasDel pwd
=JSON.parseObject(json, new TypeReference<ResponseSaasDel>() {});

RestTemplate使用代理访问:

public static SimpleClientHttpRequestFactory getFactory() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    //单位为ms
    factory.setReadTimeout(10 * 1000);
    //单位为ms
    factory.setConnectTimeout(30 * 1000);
    // 代理的url网址或ip, port端口
    InetSocketAddress address = new InetSocketAddress(url, port);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
    factory.setProxy(proxy);
    return factory;
}
public static void main(String[] args) {
    String url = ""; // 访问链接
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setRequestFactory(getFactory());
    String result = restTemplate.getForObject(url, String.class);
    System.out.println(result);
}

若RestTemplate调用https(没有证书的https)出错:unable to find valid certification path to requested target

21:31:21.862 [main] DEBUG org.springframework.web.client.RestTemplate - Accept=[text/plain, application/json, application/x-jackson-smile, application/cbor, application/*+json, */*]
Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://xxx/xx/xx": sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:751)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:318)
    at com.bailian.bidding.controller.DemoController.main(DemoController.java:231)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

解决错误:

public static HttpComponentsClientHttpRequestFactory generateHttpsRequestFactory() {
    try {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory connectionSocketFactory =
                new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
        // 代理url, port
        httpClientBuilder.setProxy(new HttpHost(url, port, "http"));
        CloseableHttpClient httpClient = httpClientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        factory.setConnectTimeout(10 * 1000);
        factory.setReadTimeout(30 * 1000);
        return factory;
    } catch (Exception e) {
        log.error("创建HttpsRestTemplate失败", e);
        throw new RuntimeException("创建HttpsRestTemplate失败", e);
    }
}
public static void main(String[] args) {
    String url = ""; // 访问链接
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setRequestFactory(generateHttpsRequestFactory());
    String result = restTemplate.getForObject(url, String.class);
    System.out.println(result);
}

原文链接:https://blog.csdn.net/likekobe2012/article/details/82663725  https://www.jianshu.com/p/21a63677c4a1

posted @ 2019-11-26 14:54  21karat  阅读(343)  评论(0)    收藏  举报