springboot使用RestTemplate详细说明

优雅的http客户端

注意,我测试的接口返回类型全部是String 类型,所以ResponseType 全部是String.class,所以请根据实际情况,酌情修改!

1 不带参数的GET请求
        // 方式1: 返回是一个response 对象
        ResponseEntity forEntity = restTemplate.getForEntity("http://127.0.0.1:1234/test1", String.class);
        System.out.println("1-getForEntry--->" + forEntity.getStatusCode() + forEntity.getBody());
        // 方式2: 返回是一个POJO
        String forObject = restTemplate.getForObject("http://localhost:1234/test1", String.class);
        System.out.println("1-getForObject--->" + forObject.toString());

2 带参数的GET请求方式PathAverable
        /**
         *@ desc : 带参数的GET请求  PathVarable
         */
        // 方式1: 返回是一个response 对象
        ResponseEntity forEntity2 = restTemplate.getForEntity("http://localhost:1234/test2/{1}/{2}", String.class, 1, 2);
        System.out.println("2-getForObject--->" + forEntity2.getStatusCode() + forEntity2.getBody().toString());
        // 方式2: 返回是一个POJO
        String forObject2 = restTemplate.getForObject("http://localhost:1234/test2/{1}/{2}", String.class, 1, 2);
        System.out.println("2-getForEntry--->" + forObject2.toString());

        

        /**
         *@ desc : 带参数的GET请求  PathVarable  方式2 map
         */
        // 方式1: 返回是一个response 对象

        HashMap map = new HashMap<>();
        map.put("param", "1");
        map.put("param2", "2");

        ResponseEntity forEntity2_1 = restTemplate.getForEntity("http://localhost:1234/test2/{param}/{param2}", String.class, map);
        System.out.println("2-1-getForObject--->" + forEntity2_1.getStatusCode() + forEntity2_1.getBody());
//         方式2: 返回是一个POJO
        String forObject2_2 = restTemplate.getForObject("http://localhost:1234/test2/{param}/{param2}", String.class, map);
        System.out.println("2-2-getForEntry--->" + forObject2_2);

3 带参数的GET请求 RequestParam

你需要一个拼接url的工具类方法,不过不要紧,我已经给你写好了

    /**
     * @ desc : 把参参数 用 xxx=xxx&xxx=xxx 形式
     */
    private static String paramToUrl(String url, HashMap map) {

        String s = map.entrySet().parallelStream().map(
                m -> m.getKey() + "=" + m.getValue()
        ).collect(Collectors.joining("&"));

        return url + "?" + s;
    }

然后

        /**
         *@ desc : 带参数的GET请求  RequestParam
         */
        HashMap map2 = new HashMap<>();
        map2.put("param", "1");
        map2.put("param2", "2");

        // 方式1: 返回是一个response 对象
        ResponseEntity forEntity3 = restTemplate.getForEntity(paramToUrl("http://localhost:1234/test3", map2), String.class);
        System.out.println("3-getForObject--->" + forEntity3.getStatusCode() + forEntity3.getBody().toString());
        // 方式2: 返回是一个POJO
        String forObject3 = restTemplate.getForObject(paramToUrl("http://localhost:1234/test3", map2), String.class);
        System.out.println("3-getForEntry--->" + forObject3.toString());
        
4 POST 请求

post 请求的body 使用了HttpEntity,httpEntity 包含header 和body,如下

        RestTemplate restTemplate = new RestTemplate();

        JSONObject body = new JSONObject();

        body.put("name", "ligen");
        body.put("age", 20);
        body.put("hobit", "game");

        HttpEntity entry = new HttpEntity<>(body);


        // 方式1: 返回是一个response 对象
        ResponseEntity forEntity4 = restTemplate.postForEntity("http://localhost:1234/test4", entry, String.class);
        System.out.println("4-postForObject--->" + forEntity4.getStatusCode() + forEntity4.getBody());
        // 方式2: 返回是一个POJO
        ResponseEntity forObject4 = restTemplate.postForEntity("http://localhost:1234/test4", entry, String.class);
        System.out.println("4-postForEntry--->" + forObject4.toString());
 
  
5 GET 怎么添加Header

上面的示例中,只有Post 参数的传递使用了HttpEntity,在HttpEntity 中我们可以快乐的定义自己的header和body,那么在GET请求中,我们需要添加Header,改怎么添加呢? 经常会有这样的场景,需要在请求头上添加token。。。不好意思,GET 不能直接添加Header。。这种情况下,你就需要使用exchange 方法。

exchange 方法是全能的,因为它允许我们在参数上指定请求方式,并且参数用的是HttpEntity。 那么它当然可以应付上面任何一种情况。真香!!!

如下


        RestTemplate restTemplate = new RestTemplate();

        // 设置Header
        HttpHeaders head = new HttpHeaders();
        head.add("token", "aaaaaaaaa");

        // 设置请求 如果是Get  body 可以设置为null, 如果是POST 直接设置body
        HttpEntity entity = new HttpEntity<>(null, head);

        // 发送请求
        ResponseEntity exchange = restTemplate.exchange("http://localhost:1234/test1/{1}/{2}", HttpMethod.GET, entity, String.class,1,2);

 
  
6 配置SSL,发送https请求

网上配置ssl的方式有很多,找到一种简单的,经过验证确实可用,如下
1 添加依赖

        
        
            org.apache.httpcomponents
            httpclient
            4.5.12
            compile
        

2 添加一个配置类

@Configuration
public class SSLConfig {

    @Bean
    public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext,
                new String[]{"TLSv1"},
                null,
                NoopHostnameVerifier.INSTANCE);

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

        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();

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

然后在需要用到 restTemplate的时候,直接使用@Autowire这个Bean,然后进行请求即可

你可能感兴趣的:(springboot,JAVA)