RestTemplate访问Restful接口
程序员文章站
2022-06-26 11:54:56
...
简介:
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。一般情况下java代码里访问restful服务,使用Apache
的HttpClient
。不过此种方法使用起来太过繁琐。
定义一个简单的Restful接口
@Controller
@RequestMapping("tpservice")
public class Tpservice {
@ResponseBody
@RequestMapping(value = "singleRecordSearch",method = RequestMethod.GET)
public String JsonTest(@RequestParam String hphm,@RequestParam String hpzl) {
ReturnValue r = new ReturnValue();
TrafficPermit t = new TrafficPermit();
t.setHphm("津A12345");
t.setHpzl("01");
t.setJxsd("周一、周五&07:00-09:00&早高峰,周二、周三&07:00-09:00&晚高峰");
t.setTxqsrq(new Date());
t.setTxjzrq(new Date());
t.setTxxl("米东区/稻香南路,米东区/东华北路");
t.setTxzbh("NO.123456789");
t.setTxzmc("中型车通行证");
r.setCode(1);
r.setMessage("成功");
r.setData(t);
return JSON.toJSONString(r);
}
}
使用RestTemplate访问该服务
1、封装成工具类HttpTools
public class HttpTools{
public static ReturnValue sendPostRequest(String url, MultiValueMap<String, String> params){
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpMethod method = HttpMethod.GET;
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
ResponseEntity<ReturnValue> response = client.exchange(url, method, requestEntity, ReturnValue.class);
return response.getBody();
}
}
2、访问测试:
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
/*封装参数,有几个封装几个*/
params.add("hphm", pv.getHphm());
params.add("hpzl", pv.getHpzl());
ReturnValue rv = HttpTools.sendPostRequest("http://"+tpsIp+":"+tpsPort+"/"+tpsMethodPath+"", params);
public class ReturnValue {
private int code;
private String message;
private TrafficPermitSyn data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public TrafficPermitSyn getData() {
return data;
}
public void setData(TrafficPermitSyn data) {
this.data = data;
}
}