restTemplate中如何进行post请求呢?

书欣 Spring 发布时间:2023-01-02 17:25:25 阅读数:16604 1
下文笔者讲述RestTemplate中进行post请求的方法分享,如下所示
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());
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/Spring/202301/5257.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者