标签:接收 入参 users ring variable run intercept json对象 tco
? spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。
? 在Spring应用程序中访问第三方REST服务与使用Spring RestTemplate类有关。RestTemplate类的设计原则与许多其他Spring *模板类(例如JdbcTemplate、JmsTemplate)相同,为执行复杂任务提供了一种具有默认行为的简化方法。
? RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。
? 考虑到RestTemplate类是为调用REST服务而设计的,因此它的主要方法与REST的基础紧密相连就不足为奇了,后者是HTTP协议的方法:HEAD、GET、POST、PUT、DELETE和OPTIONS。例如,RestTemplate类具有headForHeaders()、getForObject()、postForObject()、put()和delete()等方法。
RestTemplate包含以下几个部分:
HttpMessageConverter 对象转换器
ClientHttpRequestFactory 默认是JDK的HttpURLConnection
ResponseErrorHandler 异常处理
ClientHttpRequestInterceptor 请求拦截器
请求接口
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/users")
public String getUser1(String username, HttpServletRequest request){
return "传入的参数"+username;
}
@GetMapping("/users/{username}")
public String getUser2(@PathVariable String username){
return "传入的参数"+username;
}
}
get请求测试
@Test
public void restfulGet(){
RestTemplate restTemplate=new RestTemplate();
String url = "http://127.0.0.1:8081/test/users?username={username}";
String url2 = "http://127.0.0.1:8081/test/users/laowan";
//1、使用getForObject请求接口, 顺序传入参数
String result1 = restTemplate.getForObject(url, String.class, "你好");
System.out.println("result1====================" + result1);
//2、使用getForObject请求接口 使用HashMap传入参数
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("username", "laowan");
String result2 = restTemplate.getForObject(url, String.class, paramMap);
System.out.println("result2====================" + result1);
//3、使用url路径变量PathVariable
String result3 = restTemplate.getForObject(url2, String.class);
System.out.println("result3====================" + result3);
//4、使用exchange请求接口
ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET, null, String.class,paramMap);
System.out.println("result4====================" + response2.getBody());
//5、使用exchange请求接口,可以封装HttpEntity对象传递header参数
HttpHeaders headers = new HttpHeaders();
headers.set("username", "laowan");
HttpEntity httpEntity = new HttpEntity(null,headers);
ResponseEntity<String> response5 = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class,paramMap);
System.out.println("result5====================" + response5.getHeaders());
}
注意事项
请求接口
@PostMapping("/user")
public User addUser(String username,Integer age){
User user = new User();
user.setAge(age);
user.setUsername(username);
log.info("新增用户{}", JSON.toJSONString(user));
return user;
}
@PostMapping("/user/add")
public User addUser(User user){
log.info("新增用户{}", JSON.toJSONString(user));
return user;
}
@PostMapping("/user/json")
public User addUserJson(@RequestBody User user){
log.info("新增用户{}", JSON.toJSONString(user));
return user;
}
实体类
@Data
public class User {
private String username;
private Integer age;
}
post请求测试
String url = "http://127.0.0.1:8081/test/user";
//传统表单方式请求
RestTemplate template = new RestTemplate();
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("username", "hrllo");
paramMap.add("age", 66);
User user = template.postForObject(url, paramMap, User.class);
log.info("result1的结果为:{}",user);
//使用json方式请求
String url3 = "http://127.0.0.1:8081/test/user/json";
RestTemplate restTemplate = new RestTemplate();
//创建json对象
User user1 = new User();
user1.setUsername("张三");
user1.setAge(66);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity1 = new HttpEntity<String>(JSON.toJSONString(user1),headers);
ResponseEntity<User> resp1 = restTemplate.postForEntity(url3,entity1, User.class);
log.info("result2的结果为:{}",resp1.getBody());
//通过exchange调用post请求,传递json格式参数
HttpEntity<String> entity2 = new HttpEntity<String>(JSON.toJSONString(user1),headers);
ResponseEntity<User> resp2 = restTemplate.exchange(url3, HttpMethod.POST, entity2, User.class);
log.info("result3的结果为:{}",resp2.getBody());
//通过exchange调用post请求,传递x-www-form-urlencoded格式参数
String url2 = "http://127.0.0.1:8081/test/user/add";
MultiValueMap<String, Object> paramMap3 = new LinkedMultiValueMap<String, Object>();
paramMap.add("username", "laowan");
paramMap.add("age", 22);
HttpHeaders headers3 = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> entity3 = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
ResponseEntity<User> resp3 = restTemplate.exchange(url2, HttpMethod.POST, entity3, User.class);
if( resp3.getStatusCode().equals( HttpStatus.OK )){
log.info("result4的结果为:{}",resp3.getBody());
}else{
throw new RuntimeException( resp3.toString() );
}
注意事项
标签:接收 入参 users ring variable run intercept json对象 tco
原文地址:https://www.cnblogs.com/balloon72/p/13185403.html