spring cloud 中使用RestTemplate Post请求遇到的坑

要调用的接口服务名:TestA

@RequestMapping(value = "/hi", method = RequestMethod.POST)
    @ResponseBody
    public String hi(@RequestParam String serviceName,@RequestParam String serviceValue){
        
    	return serviceName+" "+serviceValue;
    }

服务:TestB使用RestTemplate调用服务TestA接口

@RequestMapping(value = "/api/test")
	@ResponseBody
	public String order() throws InterruptedException {
		
		MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
		param.add("serviceName", "serviceName");
		param.add("serviceValue", "serviceValue");
		
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/x-www-form-urlencoded");
		
		HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(param, headers);
		
		//含有请求头
		String result = restTemplate.postForObject("http://127.0.0.1:9003/hi", formEntity, String.class);
		//不含请求头
//		String result = restTemplate.postForObject("http://127.0.0.1:9003/hi", param, String.class);
		return result;
	}

使用注意:

        1.加上@ResponseBody

        2.MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();

            注意使用是org.springframework.util.MultiValueMap包里的MultiValueMap

       3.RestTemplate会对请求头判断,会更具请求头不通走不同的逻辑。默认是 text/html  
          如果是  application/x-www-form-urlencoded  这个请求头  会对数据镜像 url 编码。
          不可以传递 非 字符串类型的数据!

        4.String result = restTemplate.postForObject("http://127.0.0.1:9003/hi", formEntity, String.class);

           如果使用的ip访问,那么不需要加@LoadBalanced

@Bean
	 RestTemplate restTemplate() {
		 return new RestTemplate();
	 }

            String result = restTemplate.postForObject("http://TestA/hi", formEntity, String.class);

            如果使用是服务名访问,那么需要加上@LoadBalanced

@Bean
	 @LoadBalanced
	 RestTemplate restTemplate() {
		 return new RestTemplate();
	 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涛哥是个大帅比

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值