Java日常学习

RestTemplate的用法

2020-12-25  本文已影响0人  LeslieFind

一、发送get请求:

1、只有url的

        ## 1、实例化RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();
        ## 2、获取Entity,使用getBody()获取响应体
        Object oldResp = restTemplate.getForEntity(oldUrl,Map.class).getBody();

2、有header信息

        String url = "http://test.234.cn";
        ## 1、实例化RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();
        ## 2、实例化HttpHeaders对象
        HttpHeaders headers = new HttpHeaders();
        ## 3、添加header
        headers.add("Cookie","_cookie_enable=null");
        headers.add("Referer","http://test.234.cn");
        ##4、创建httpEntity对象,传入headers
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ## 5、restTemplate发送请求,用exchange()
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET,entity,String.class);
        System.out.println(response.getBody());
上一篇 下一篇

猜你喜欢

热点阅读