HTTP客户端

未匹配的标注

在 Spring Boot 中,最接近 PHP 的 cURL 或 Guzzle 的库是 RestTemplate(同步)和 WebClient(异步)。以下是详细对比和推荐方案:


1. 最接近 PHP cURL 的库:RestTemplate
特点
• 同步阻塞:和 PHP 的 cURL 一样,发送请求后等待响应,适合简单场景。

• 链式配置:支持设置 Headers、超时、代理等,类似 cURL 的 curl_setopt

• 直接返回结果:无需处理异步回调,代码直观。

示例代码(类似 cURL)

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

public String fetchWithRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();

    // 设置Headers(类似 cURL 的 CURLOPT_HTTPHEADER)
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer token");
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> requestEntity = new HttpEntity<>(headers);

    // 发送GET请求(类似 curl_exec)
    ResponseEntity<String> response = restTemplate.exchange(
        "https://api.example.com/data",
        HttpMethod.GET,
        requestEntity,
        String.class
    );

    return response.getBody();
}

关键操作对比
| PHP cURL 功能 | RestTemplate 等效操作 |
|————————-|————————————|
| curl_init() | new RestTemplate() |
| curl_setopt() | HttpHeaders / RequestEntity |
| curl_exec() | restTemplate.exchange() |
| curl_error() | 捕获 HttpClientErrorException |


2. 最接近 Guzzle 的库:WebClient
特点
• 异步非阻塞:类似 Guzzle 的 Promise 机制,适合高并发。

• 流畅的 API:链式调用风格和 Guzzle 高度相似。

• 响应式支持:基于 Reactor 库(类似 Guzzle 的 PSR-7)。

示例代码(类似 Guzzle)

import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

public Mono<String> fetchWithWebClient() {
    return WebClient.create()
        .get()
        .uri("https://api.example.com/data")
        .header("Authorization", "Bearer token")
        .retrieve()
        .bodyToMono(String.class)
        .onErrorResume(e -> Mono.error(new RuntimeException("请求失败")));
}

关键操作对比
| Guzzle 功能 | WebClient 等效操作 |
|————————-|———————————-|
| new Client() | WebClient.create() |
| $client->get() | webClient.get() |
| ->withHeaders() | .header() / .headers() |
| ->getBody() | .bodyToMono() |
| Promise(异步) | Mono / Flux |


3. 其他类似 Guzzle 的第三方库
如果需要更接近 Guzzle 的体验,可以使用以下库:

(1) Unirest(轻量级 HTTP 客户端)
• 依赖:

  <dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>3.13.10</version>
  </dependency>

• 示例:

  HttpResponse<String> response = Unirest.get("https://api.example.com/data")
      .header("Authorization", "Bearer token")
      .asString();

(2) OkHttp(底层高效库)
• 依赖:

  <dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.3</version>
  </dependency>

• 示例:

  OkHttpClient client = new OkHttpClient();
  Request request = new Request.Builder()
      .url("https://api.example.com/data")
      .addHeader("Authorization", "Bearer token")
      .build();
  Response response = client.newCall(request).execute();

4. 如何选择?
| 需求场景 | 推荐工具 |
|————————–|———————–|
| 需要最像 cURL 的同步请求 | RestTemplate |
| 需要类似 Guzzle 的异步流 | WebClient |
| 追求轻量级和简单语法 | Unirest |
| 需要底层高性能控制 | OkHttp |


5. 完整示例(RestTemplate + 异常处理)

import org.springframework.http.*;
import org.springframework.web.client.*;

public String fetchDataWithCurlStyle() {
    RestTemplate restTemplate = new RestTemplate();
    try {
        ResponseEntity<String> response = restTemplate.exchange(
            "https://api.example.com/data",
            HttpMethod.GET,
            new HttpEntity<>(new HttpHeaders()),
            String.class
        );
        return response.getBody();
    } catch (HttpClientErrorException e) {
        System.err.println("HTTP错误: " + e.getStatusCode());
    } catch (ResourceAccessException e) {
        System.err.println("网络错误: " + e.getMessage());
    }
    return null;
}

总结
• 直接替代 cURL:用 RestTemplate(同步简单)或 OkHttp(更底层)。

• 替代 Guzzle:用 WebClient(异步流畅)或 Unirest(语法简洁)。

• Spring Boot 默认推荐:优先使用 WebClient(未来趋势)。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
唐章明
讨论数量: 0
发起讨论 只看当前版本


暂无话题~