RestTemplate用法

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方法如下:

getForObject方法如下圖

客戶端的controller:
@GetMapping("{id}")
public HashMap show(@PathVariable("id")Integer id){
	//空的入參
	Map<Integer,User> map=new HashMap<>();
    String	u_url="//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="//server82/user/list";
	 List<User> user=(List<User>) restTemplate.getForObject(u_url,List.class);
	 return  user;
	
}

這是getForObject()的其中一個方法的使用