在Spring框架中,RestTemplate是传统的同步客户端,用于发起HTTP请求,而WebClient是Spring 5中引入的,支持同步和异步、非阻塞的客户端,是RestTemplate的现代替代品。下面是如何使用这两个客户端来实现你的需求的具体代码示例。
使用RestTemplate
首先,我们将创建一个RestTemplate的工具类:
java复制
解释
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
public class RestTemplateUtil {
private static final String URL = "你的URL"; // 请替换成你的实际URL
private RestTemplate restTemplate;
public RestTemplateUtil() {
this.restTemplate = new RestTemplate();
}
public ResponseEntity<String> submitFormWithHeaders(String orderId, String goods) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("appId", "qwerre");
headers.add("user", "1234");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("orderId", orderId);
map.add("goods", goods);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
return restTemplate.postForEntity(URL, request, String.class);
}
}
你可以通过创建RestTemplateUtil的实例并调用submitFormWithHeaders方法来使用它。
使用WebClient
同样地,我们创建一个WebClient的工具类:
java复制
解释
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class WebClientUtil {
private static final String URL = "你的URL"; // 请替换成你的实际URL
private WebClient webClient;
public WebClientUtil() {
this.webClient = WebClient.create();
}
public Mono<String> submitFormWithHeaders(String orderId, String goods) {
return webClient.post()
.uri(URL)
.header("appId", "qwerre")
.header("user", "1234")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.bodyValue("orderId=" + orderId + "&goods=" + encodeValue(goods))
.retrieve()
.bodyToMono(String.class);
}
private String encodeValue(String value) {
try {
return java.net.URLEncoder.encode(value, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
在这个例子中,submitFormWithHeaders方法将返回一个Mono<String>,它是一个响应式类型,代表在将来某个时点可能会有一个String类型的响应。如果你想要阻塞等待这个值,可以在调用的地方使用.block()方法。
请注意,这两个工具类中的URL应该替换为你实际要请求的URL,同时,你应该将这些工具类注册为Spring的Bean,以便在你的应用中得到更好的管理和配置。