restTemplate中如何进行post请求呢?
下文笔者讲述RestTemplate中进行post请求的方法分享,如下所示
postForObject示例
RestTemplate中进行post请求 我们可采用postForObject方法或postForEntity方法 实现post请求 具体的操作方法,如下所示
postForObject()语法
public <T> T postForObject(String url, @Nullable Object request,
Class<T> responseType, Object... uriVariables)
throws RestClientException {}
public <T> T postForObject(String url, @Nullable Object request,
Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException {}
public <T> T postForObject(URI url, @Nullable Object request,
Class<T> responseType) throws RestClientException {}
例:postForObject示例
post请求
提交参数 Student 对象
RestTemplate代码
String url = "http://localhost:9999/testPostFunForObject";
Student student = new Student();
student.setName("java-name");
student.setAge("23");
String msg = restTemplate.postForObject(url , student , String.class);
服务端代码:
@RequestMapping("/testPostFunForObject")
public String testPostFunForObject(@RequestBody Student student){
log.info("【studeng: {}】" , student);
return "success";
}
postForEntity()语法
public <T> T postForObject(String url, @Nullable Object request,
Class<T> responseType, Object... uriVariables)
throws RestClientException {}
public <T> T postForObject(String url, @Nullable Object request,
Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException {}
public <T> T postForObject(URI url, @Nullable Object request,
Class<T> responseType) throws RestClientException {}
postForEntity()示例
@RequestMapping("/testPostFunForEntity")
public void testPostFunForEntity(){
String url = "http://localhost:9999/testPostFunForEntity";
Student student = new Student();
student.setName("java-name");
student.setAge("18");
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url , student , String.class);
log.info(responseEntity.getBody());
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


