java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot发起http请求

SpringBoot项目里面发起http请求的几种方法

作者:阿黄学技术

Spring Boot发起HTTP请求有多种方法,包括:RestTemplate,WebClient, HttpClient, Feign Client,第三方库如OkHttp和Apache HttpClient,下面就来详细的介绍一下如何实现,感兴趣的可以了解一下

在Spring Boot项目中,有几种常用的方式可以发起HTTP请求,以下是主要的几种方法:

1. 使用RestTemplate (Spring 5之前的主流方式)

// 需要先注入RestTemplate
@Autowired
private RestTemplate restTemplate;

public void makeRequest() {
    // GET请求
    ResponseEntity<String> response = restTemplate.getForEntity(
        "https://api.example.com/data", String.class);
    
    // POST请求
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> request = new HttpEntity<>("{\"key\":\"value\"}", headers);
    ResponseEntity<String> response = restTemplate.postForEntity(
        "https://api.example.com/data", request, String.class);
}

2. 使用WebClient (Spring 5+推荐的响应式方式)

// 需要添加spring-boot-starter-webflux依赖
WebClient webClient = WebClient.create();

// GET请求
Mono<String> response = webClient.get()
    .uri("https://api.example.com/data")
    .retrieve()
    .bodyToMono(String.class);

// POST请求
Mono<String> response = webClient.post()
    .uri("https://api.example.com/data")
    .contentType(MediaType.APPLICATION_JSON)
    .bodyValue("{\"key\":\"value\"}")
    .retrieve()
    .bodyToMono(String.class);

3. 使用HttpClient (Java 11+内置)

HttpClient client = HttpClient.newHttpClient();

// GET请求
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/data"))
    .build();

// POST请求
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/data"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}"))
    .build();

// 发送请求
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

4. 使用Feign Client (声明式REST客户端)

// 需要添加spring-cloud-starter-openfeign依赖
@FeignClient(name = "exampleClient", url = "https://api.example.com")
public interface ExampleClient {
    @GetMapping("/data")
    String getData();
    
    @PostMapping("/data")
    String postData(@RequestBody String body);
}

// 使用
@Autowired
private ExampleClient exampleClient;

public void makeRequest() {
    String response = exampleClient.getData();
}

5. 使用第三方库如OkHttp或Apache HttpClient

OkHttp示例:

OkHttpClient client = new OkHttpClient();

// GET请求
Request request = new Request.Builder()
    .url("https://api.example.com/data")
    .build();

// POST请求
RequestBody body = RequestBody.create(
    "{\"key\":\"value\"}", MediaType.parse("application/json"));
Request request = new Request.Builder()
    .url("https://api.example.com/data")
    .post(body)
    .build();

// 发送请求
Response response = client.newCall(request).execute();

Apache HttpClient示例:

CloseableHttpClient httpClient = HttpClients.createDefault();

// GET请求
HttpGet httpGet = new HttpGet("https://api.example.com/data");

// POST请求
HttpPost httpPost = new HttpPost("https://api.example.com/data");
StringEntity entity = new StringEntity("{\"key\":\"value\"}");
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/json");

// 发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);

选择建议

到此这篇关于SpringBoot项目里面发起http请求的几种方法的文章就介绍到这了,更多相关SpringBoot发起http请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文