springboot 2.0 整合 RestTemplate 與使用教程
首先匯入springboot 的 web 包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
在啟動類同包下建立RestTemplate.java類
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(15000); factory.setReadTimeout(5000); return factory; } }
然後在Service類中注入使用即可
@Service
public class demoService {
@Autowired
private RestTemplate restTemplate;
public String get(Integer id){
return restTemplate.getForObject("http://localhost:8080/user?userId=id",String.class);
}
}
RestTemplate定義了36個與REST資源互動的方法,其中的大多數都對應於HTTP的方法。 其實,這裡面只有11個獨立的方法,其中有十個有三種過載形式,而第十一個則過載了六次,這樣一共形成了36個方法。
delete() 在特定的URL上對資源執行HTTP DELETE操作
exchange() 在URL上執行特定的HTTP方法,返回包含物件的ResponseEntity,這個物件是從響應體中對映得到的
execute() 在URL上執行特定的HTTP方法,返回一個從響應體對映得到的物件
getForEntity() 傳送一個HTTP GET請求,返回的ResponseEntity包含了響應體所對映成的物件
getForObject() 傳送一個HTTP GET請求,返回的請求體將對映為一個物件
postForEntity() POST 資料到一個URL,返回包含一個物件的ResponseEntity,這個物件是從響應體中對映得到的
postForObject() POST 資料到一個URL,返回根據響應體匹配形成的物件
headForHeaders() 傳送HTTP HEAD請求,返回包含特定資源URL的HTTP頭
optionsForAllow() 傳送HTTP OPTIONS請求,返回對特定URL的Allow頭資訊
postForLocation() POST 資料到一個URL,返回新建立資源的URL
put() PUT 資源到特定的URL
getForEntity
get請求就和正常在瀏覽器url上傳送請求一樣
下面是有引數的get請求
@GetMapping("getForEntity/{id}")
public User getById(@PathVariable(name = "id") String id) {
ResponseEntity<User> response = restTemplate.getForEntity("http://localhost/get/{id}", User.class, id);
User user = response.getBody();
return user;
}
getForObject
getForObject 和 getForEntity 用法幾乎相同,指示返回值返回的是 響應體,省去了我們 再去 getBody()
@GetMapping("getForObject/{id}")
public User getById(@PathVariable(name = "id") String id) {
User user = restTemplate.getForObject("http://localhost/get/{id}", User.class, id);
return user;
}
postForEntity
@RequestMapping("saveUser")
public String save(User user) {
ResponseEntity<String> response = restTemplate.postForEntity("http://localhost/save", user, String.class);
String body = response.getBody();
return body;
}
postForObject
用法與 getForObject 一樣
如果遇到 postForObject 方法在 Controller 接受不到引數問題 請參考的的另一篇部落格 :
exchange
@PostMapping("demo")
public void demo(Integer id, String name){
HttpHeaders headers = new HttpHeaders();//header引數
headers.add("authorization",Auth);
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject obj = new JSONObject();//放入body中的json引數
obj.put("userId", id);
obj.put("name", name);
HttpEntity<JSONObject> request = new HttpEntity<>(content,headers); //組裝
ResponseEntity<String> response = template.exchange("http://localhost:8080/demo",HttpMethod.POST,request,String.class);
}
其餘的方法用法也都差不多 , 在此就不細說了