使用springboot主动发送Http请求


    @Test
    void contextLoads() {
        //使用RestTemplate主动发送HttpGET请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Video> video1 = restTemplate.getForEntity("http://www.baidu,com", Video.class);
        System.out.println(video1);

        //URL参数可以使用restful风格,当然也可以直接的URL参数拼接执行
        ResponseEntity<Video> video2 = restTemplate.getForEntity("http://www.baidu,com/{1}/{2}", Video.class, 1, 2);
        System.out.println(video2);

        //高级一点的写法
        Map<String,String> map = new HashMap();
        map.put("start","1");
        map.put("page","5");
        Video video3 = restTemplate.getForObject("http://www.baidu,com/", Video.class, map);

        //getForObject()其实比getForEntity()多包含了将HTTP转成POJO的功能,但是getForObject没有处理response的能力。
        // 因为它拿到手的就是成型的pojo。省略了很多response的信息。如果需要转换成pojo,还需要json工具类的引入。

        //======================================================================================================

        //使用RestTemplate主动发送HttpPOST请求
        String url = "http://www.baidu.com";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map1= new LinkedMultiValueMap<>();
        map1.add("email", "844072586@qq.com");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map1, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
        System.out.println(response.getBody());
    }
    

方法很简单,源码的复杂度也不高,可以看看。

引用链接springboot发送http请求

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值