猫咪家
首页
分类
标签
归档
关于
管理员
2021-03-18
1241
RestTemplate 发送Post Json请求,并携带HttpHeaders
```java pom依赖 <parent> <artifactId>spring-boot-starter-parent</artifactId> <groupId>org.springframework.boot</groupId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.8.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.30</version> </dependency> </dependencies> 使用okhttp初始化restTemplate,启动类中添加 @Bean public RestTemplate restTemplate() { return new RestTemplate(new OkHttp3ClientHttpRequestFactory()); } 测试接口 被restTemplate调用的接口 @PostMapping("/get/user") public User getUser(@RequestBody User user, HttpServletRequest request) { String token = request.getHeader("token"); System.out.println(token); User newUser = new User(); newUser.setId(110); newUser.setName("警察"); BeanUtils.copyProperties(newUser, user, "desc", "note"); return user; } 用到的实体类 @RestController public class TestController { @Autowired private RestTemplate restTemplate; @RequestMapping("/test/restTemplate") public User testTemplate() { String url = "http://localhost:9999/get/user"; User user = new User(); user.setDesc("desc"); user.setNote("note"); // 方式一 HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); // 添加额外http请求头参数 headers.add("token","123456"); HttpEntity<String> request = new HttpEntity<String>(JSONObject.toJSON(user).toString(), headers); User u = restTemplate.postForObject(url, request, User.class); /* // 方式二 不需要传HttpHeaders的情况使用 ResponseEntity<User> userResponseEntity = restTemplate.postForEntity(url, user, User.class); HttpStatus statusCode = userResponseEntity.getStatusCode(); boolean xxSuccessful = statusCode.is2xxSuccessful(); if(xxSuccessful){ return userResponseEntity.getBody(); } */ return u; } } ```
###Hello world!
Springboot
评论
发布
留言
评论