RestTemplate get请求,header设置及传参方式

Spring Boot RestTemplate使用get请求,请求头header的设置及传参方式

  1. 有参数,没有请求头
  2. 有请求头,没参数
  3. 有请求头,有参数
@RestController
@Api(tags = "测试")
@RequestMapping("/test")
public class HttpController{
    
    @Autowired
    private RestTemplate restTemplate;
    
    /**
     * 测试
     */
    @RequestMapping(value = "/http", method = RequestMethod.GET)
    @ApiOperation(value = "测试http")
    public String http() {
        String id = "52db70d13ad74b0f85142e39b32164b4";
        String name = "测试";
        //参数
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
        param.add("id", id);
        param.add("name", name);
        
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("accessToken", "3d40e41e9d764d30a9a4d72e61ad61b9");
        
        //封装请求头
        HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(headers);
        
        try {
            //访问地址
            String url = "http://localhost:8080/testservice/test/get";
            
            //1. 有参数,没有请求头,拼接方式
            String result1 = restTemplate.getForObject(url + "?id="+id+"&name="+name, String.class);
            //2. 有参数,没有请求头,占位符方式
            String result2 = restTemplate.getForObject(url + "?id={id}&name={name}", String.class, param);
            //3. 有请求头,没参数,result3.getBody()获取响应参数
            ResponseEntity<String> result3 = restTemplate.exchange(url, HttpMethod.GET, formEntity, String.class);
            //4. 有请求头,有参数,result4.getBody()获取响应参数
            ResponseEntity<String> result4 = restTemplate.exchange(url+"?id="+id+"&name="+name, HttpMethod.GET, formEntity, String.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
}
————————————————                          
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值