当然,以下是一个简单的示例,演示如何在Spring Boot中创建一个HttpUtils工具类,用于发送HTTP请求:
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
public class HttpUtils {
private final RestTemplate restTemplate;
public HttpUtils(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public ResponseEntity<String> sendGetRequest(String url, MultiValueMap<String, String> headers) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.addAll(headers);
HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
return restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
}
public ResponseEntity<String> sendPostRequest(String url, MultiValueMap<String, String> headers, String requestBody) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.addAll(headers);
HttpEntity<String> httpEntity = new HttpEntity<>(requestBody, httpHeaders);
return restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
}
// 可以根据需要添加其他类型的HTTP请求方法,例如PUT、DELETE等
}
在上述代码中,我们使用了RestTemplate来发送HTTP请求。您可以在Spring Boot中注入一个RestTemplate的实例,并在HttpUtils的构造函数中将其传递进来。
然后,HttpUtils类提供了sendGetRequest和sendPostRequest方法来发送GET和POST请求,您可以根据需要添加其他类型的HTTP请求方法。
这只是一个简单的示例,您可以根据自己的实际需求来扩展和修改HttpUtils类的功能。