RestTemplate 用法
  Cizx3FC6OyJR 2023年11月12日 34 0

RestTemplate 用法

RestTemplate简介
  1. RestTemplate 是一个同步的web http客户端请求模板工具,spring框架做的抽象模板,

  2. 常见的http客户端请求工具有:

    JDK的HttpURLConnection

    apache的HttpClient

    常见的 OkHttp

    3.一般默认用的是:HttpURLConnection如下

     //底层执行引擎httpUrlconnection
     RestTemplate tempalte=new RestTemplate(new     HttpComponentsClientHttpRequestFactory());
    

    4.RestTemplate常见的请求方式:Get和Post

    Get请求方式方法有getforentity ,getforobject

    getForEntity方法如下:

    1 1.png

    getForObject方法如下图

1 2.png 5.

客户端的controller:
@GetMapping("{id}")
public HashMap show(@PathVariable("id")Integer id){
	//空的入参
	Map<Integer,User> map=new HashMap<>();
    String	u_url="http://server82/user/get/"+id;
    ResponseEntity<HashMap> user=restTemplate.getForEntity(u_url,HashMap.class,map);
    
	return user.getBody();
}

<!--这是用的getForEntity()中的一个方法,这里没有写状态码,它与getForObject()方法的区别是这个方法可以返回状态码,在用这些方法时注意参数返回的类型-->

客户端的controller
@GetMapping("index2")
public Object All(){
	 String	u_url="http://server82/user/list";
	 List<User> user=(List<User>) restTemplate.getForObject(u_url,List.class);
	 return  user;
	
}

<!--这是getForObject()的其中一个方法的使用-->

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月12日 0

暂无评论

推荐阅读
Cizx3FC6OyJR
作者其他文章 更多

2023-11-12