RestTemplate 发送Post Json请求,并携带Ht
2019-10-09 本文已影响0人
大黑跟小白的日常
springboot项目
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;
}
用到的实体类
@Data
class User {
private Integer id;
private String name;
private String desc;
private String note;
}
浏览器直接访问测试接口
@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;
}
}