1. Spring提供了一個RestTemplate模板工具類,對基於Http的客戶端進行了封裝,並且實現了對象與json的序列化和反序列化,非常方便。RestTemplate並沒有限定Http的客戶端類型,而是進行了抽象,目前常用的3種都有支持:
- HttpClient
- OkHttp
- JDK原生的URLConnection(默認的)
2. RestTemplate 使用步驟
2.1 首先在項目中註冊一個`RestTemplate`對象,可以在啓動類位置註冊:
package com.guo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
public class EurekaConsumer2Application {
public static void main(String[] args) {
SpringApplication.run(EurekaConsumer2Application.class, args);
}
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
2.2 在controller類中直接`@Autowired`注入:
package com.guo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class GetUserController {
@Autowired
RestTemplate restTemplate;
@RequestMapping("/user")
public String userString() {
String str = restTemplate.getForObject("http://localhost:9081/getUser", String.class);
return str;
}
}