SpringBoot请求工具http客户端
HTTP客户端请求工具
RestTemplate
在SpringBoot 中最常见的就是RestTemplate了
java
public void test() {
String forObject = restTemplate
.getForObject("http://127.0.0.1:8999/hello", String.class);
}
简单的方式就可以快速请求工具了
OkHttp
xml
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
常见的方法也适用
java
public void test() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://localhost:8080/api/v1/users")
.build();
Response response = client.newCall(request).execute();
}
不过在SpringBoot3新版本中被移除了
RestClient
RestClient是Spring6的产物,操作方式和RestTemplate差不多
java
public void test() {
String body = restClient
.get()
.uri("http://127.0.0.1:8999/hello")
.retrieve()
.body(String.class);
}
WebClient
WebClient是在响应式框架中用到的客户端请求工具
- 需要先导入webflux包
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
java
public void test() {
WebClient webClient = WebClient.builder().build();
webClient
.get()
.uri("http://localhost:8080/hello")
.retrieve().bodyToMono(String.class);
}
SpringBoot客户端请求方式
在新版SpringBoot中可以安装OpenFein的方式封装接口
HttpApiConfig.java
java
@Configuration
public class HttpApiConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public RestClient restClient() {
return RestClient.builder()
.build();
}
@Bean
public WebClient webClient() {
WebClient webClient = WebClient.builder().build();
webClient.get().uri("http://localhost:8080/hello").retrieve().bodyToMono(String.class);
return WebClient
.builder()
.build();
}
@Bean
public RemoteApi restTemplateRemoteApi(RestTemplate restTemplate) {
return HttpServiceProxyFactory
.builderFor(RestTemplateAdapter
.create(restTemplate))
.build()
.createClient(RemoteApi.class);
}
@Bean
public RemoteApi restClientRemoteApi(RestClient restClient) {
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build()
.createClient(RemoteApi.class);
}
@Bean
public RemoteApi webClientRemoteApi(WebClient webClient) {
return HttpServiceProxyFactory
.builderFor(WebClientAdapter.create(webClient))
.build()
.createClient(RemoteApi.class);
}
}
封装客户端请求接口
java
@HttpExchange("http://locallhost:8999")
public interface RemoteApi {
@GetExchange("/hello")
String hello();
@PostExchange("/hello")
String postHello();
@PutExchange("/hello")
String putHello();
@DeleteExchange("/hello")
String deleteHello();
// ...
}
java
@Resource
private RemoteApi restClientRemoteApi;
@Test
public void testRemoteApi() {
String hello = restClientRemoteApi.hello();
}
这样写起来的客户端请求更加优雅