对于不了解http协议的建议使用这个方法
restTemplate.postForObject(url,参数实体,返回实体.class)
把需要的参数实体类对象直接扔进方法第二个参数即可
如果需要携带头信息则需要对第二个参数进行封装具体如下:
HttpHeaders requestHeaders = new HttpHeaders();
我需要携带token验证,我使用的方法如下,其他同理可以自己试一试
requestHeaders.setBearerAuth("Yxxxxxxxxxxxn8_nmvLxxxxDyNczBBovg");
因为所有参数都要放到第二个位置所以使用进行封装,不管 什么参数都封装成一个对象直接扔进去,然后把头信息对象页方进去就可以了
HttpEntity requestEntity =new HttpEntity(param,requestHeaders);
最后把请求体对象放到模板对象的第二个参数即可
ResponseResult result = restTemplate.postForObject(url, requestEntity, ResponseResult.class);
案例
public ResponseResult send(){
String url="http://xxx.xxxmob.com/xxxxx/xxxx/sms/send";
List<String> phone=new ArrayList<>();
phone.add("1523xxx922");
NumberParam numberParam=new NumberParam();
numberParam.setP1("1xxx56");
numberParam.setP2("x");
HXParam param=new HXParam();
param.setMobiles(phone);
param.setTid(xx);
param.setTmap(numberParam);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setBearerAuth("YWMt2jFvhxxx5QAxxxxxUQfD8zu0pjDyNczBBovg");
HttpEntity requestEntity =new HttpEntity(param,requestHeaders);
ResponseResult result = restTemplate.postForObject(url, requestEntity, ResponseResult.class);
return result;
}
简单的get案例
1.加入ioc
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
}
2.简单调用
@Autowired
private RestTemplate restTemplate;
@GetMapping("{city}")
public String getW(@PathVariable("city")String city){
String url="http://wthrcdn.etouch.cn/weather_mini?city="+city;
String forObject = restTemplate.getForObject(url, String.class);
return forObject;
}