杰瑞科技汇

Java如何调用RESTful接口?

核心概念

无论使用哪种方法,调用 RESTful API 的基本步骤都是相似的:

Java如何调用RESTful接口?-图1
(图片来源网络,侵删)
  1. 确定请求信息
    • URL (统一资源定位符):你要访问的 API 端点,https://api.example.com/users/123
    • HTTP 方法:GET(获取)、POST(创建)、PUT(更新全部)、PATCH(更新部分)、DELETE(删除)等。
    • 请求头Content-Type(指定请求体格式,如 application/json)、Authorization(用于身份验证,如 Bearer Token)等。
    • 请求体:对于 POST、PUT、PATCH 等方法,通常需要发送数据,通常是 JSON 格式。
  2. 发送请求:将上述信息通过网络发送到服务器。
  3. 接收响应
    • 响应状态码:如 200 (OK), 201 (Created), 404 (Not Found), 500 (Server Error) 等。
    • 响应头:服务器返回的元信息。
    • 响应体:服务器返回的数据,通常也是 JSON 格式。
  4. 处理响应:解析响应体(通常是 JSON),并将其转换为 Java 对象,以便在程序中使用。

使用 HttpURLConnection (JDK 内置)

这是最基础的方法,不需要引入任何第三方库,它比较繁琐,但能让你理解 HTTP 通信的底层原理。

优点

  • JDK 自带,无需额外依赖。
  • 轻量级。

缺点

  • 代码冗长,样板代码多。
  • 处理 JSON 需要手动引入 JSON 库(如 Jackson, Gson)。
  • 功能相对较弱,例如连接池管理比较麻烦。

示例代码

假设我们要调用一个 GET 请求获取用户信息,并使用 Jackson 库来解析 JSON。

添加 Jackson 依赖

如果你使用 Maven (pom.xml):

Java如何调用RESTful接口?-图2
(图片来源网络,侵删)
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- 使用最新版本 -->
</dependency>

创建数据模型

// User.java
public class User {
    private int id;
    private String name;
    private String email;
    // Getters and Setters (以及构造函数)
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

发起 GET 请求

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
    private static final String API_URL = "https://jsonplaceholder.typicode.com/users/1";
    public static void main(String[] args) {
        try {
            // 1. 创建 URL 对象
            URL url = new URL(API_URL);
            // 2. 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3. 设置请求方法
            connection.setRequestMethod("GET");
            // 4. 设置请求头
            connection.setRequestProperty("Accept", "application/json");
            // 5. 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK
                // 6. 读取响应数据
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // 7. 解析 JSON
                ObjectMapper objectMapper = new ObjectMapper();
                User user = objectMapper.readValue(response.toString(), User.class);
                System.out.println("Parsed User: " + user);
            } else {
                System.out.println("GET request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用 Apache HttpClient (功能强大)

Apache HttpClient 是一个成熟、稳定、功能丰富的 HTTP 客户端库,比 HttpURLConnection 更强大,但配置也更复杂一些。

优点

  • 功能非常强大,支持连接池、重试、拦截器等高级特性。
  • API 比 HttpURLConnection 更人性化。
  • 社区活跃,文档完善。

缺点

  • 需要引入额外的库。
  • 配置相对繁琐。

示例代码

添加依赖

Java如何调用RESTful接口?-图3
(图片来源网络,侵删)

Maven (pom.xml):

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3.1</version> <!-- 使用最新版本 -->
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5-fluent</artifactId>
    <version>5.3.1</version> <!-- Fluent API,更简洁 -->
</dependency>

使用 Fluent API 发起请求 (推荐)

Fluent API 提供了链式调用,使代码更简洁。

import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HttpClientFluentExample {
    private static final String API_URL = "https://jsonplaceholder.typicode.com/users/1";
    public static void main(String[] args) {
        try {
            // 使用 Fluent API 发起 GET 请求
            HttpResponse response = Request.get(API_URL)
                    .addHeader("Accept", "application/json")
                    .execute();
            // 检查响应状态
            System.out.println("Response Status: " + response.getCode());
            // 获取响应体并解析
            String responseBody = response.getEntity().getContent().toString();
            ObjectMapper objectMapper = new ObjectMapper();
            User user = objectMapper.readValue(responseBody, User.class);
            System.out.println("Parsed User: " + user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用 OkHttp (现代、流行)

OkHttp 是目前 Java 和 Android 开发中最流行的 HTTP 客户端之一,它以其高效、简洁和强大的功能而闻名。

优点

  • API 非常简洁易用。
  • 性能优秀,支持 HTTP/2 和连接池。
  • 内置 JSON 解析支持(通过 okhttpokhttp-sse 等模块)。
  • 社区庞大,是许多现代框架的首选。

缺点

  • 需要引入第三方库。

示例代码

添加依赖

Maven (pom.xml):

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version> <!-- 使用最新版本 -->
</dependency>
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp-sse</artifactId>
    <version>4.12.0</version> <!-- 如果需要 Server-Sent Events -->
</dependency>

发起 GET 请求

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class OkHttpExample {
    private static final String API_URL = "https://jsonplaceholder.typicode.com/users/1";
    public static void main(String[] args) {
        // 创建 OkHttp 客户端
        OkHttpClient client = new OkHttpClient();
        // 构建 Request 对象
        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Accept", "application/json")
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 获取响应体
            String responseBody = response.body().string();
            // 解析 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            User user = objectMapper.readValue(responseBody, User.class);
            System.out.println("Parsed User: " + user);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用 Spring RestTemplate (Spring 生态)

如果你的项目是基于 Spring 或 Spring Boot 的,RestTemplate 是调用 REST API 的传统标准方式,在 Spring Boot 3.0 之后,它被 WebClient 替代为首选。

优点

  • 与 Spring 框架无缝集成。
  • 支持自动转换 JSON/XML(需要 Jackson 或 JAXB 依赖)。
  • 提供了高层次的抽象,使用非常方便。

缺点

  • 仅适用于 Spring 生态。
  • RestTemplate 是同步的,并且自 Spring Boot 3.0 起已不推荐使用。

示例代码

确保 Spring Boot 项目有相关依赖

spring-boot-starter-web 会自动包含 spring-web 和 Jackson。

使用 RestTemplate

import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
public class RestTemplateExample {
    private static final String API_URL = "https://jsonplaceholder.typicode.com/users/1";
    public static void main(String[] args) {
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(java.util.Collections.singletonList(MediaType.APPLICATION_JSON));
        // 创建请求实体
        HttpEntity<String> entity = new HttpEntity<>(headers);
        try {
            // 发起 GET 请求,并直接将响应映射为 User 对象
            User user = restTemplate.getForObject(API_URL, User.class);
            System.out.println("Parsed User: " + user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用 Spring WebClient (现代、异步)

WebClient 是 Spring 5 引入的、非阻塞的、响应式的 HTTP 客户端,是 RestTemplate 的现代替代品,也是 Spring Boot 3.x 的首选。

优点

  • 非阻塞、异步:性能更高,能更好地处理高并发。
  • 响应式编程:基于 Reactor 或 RxJava,函数式 API 风格。
  • 现代:是 Spring 生态的未来方向。

缺点

  • 学习曲线比 RestTemplate 陡峭,需要理解响应式编程。
  • 仅适用于 Spring 生态。

示例代码

import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class WebClientExample {
    private static final String API_URL = "https://jsonplaceholder.typicode.com/users/1";
    public static void main(String[] args) {
        // 创建 WebClient 实例
        WebClient webClient = WebClient.create();
        // 发起 GET 请求
        Mono<User> userMono = webClient.get()
                .uri(API_URL)
                .retrieve() // 获取响应
                .bodyToMono(User.class); // 将响应体转换为 User 对象的 Mono
        // 订阅 Mono 并处理结果
        userMono.subscribe(
                user -> System.out.println("Parsed User: " + user),
                error -> System.err.println("Error: " + error.getMessage())
        );
        // 注意:WebClient 是异步的,主线程可能已经结束了。
        // 为了看到输出,可以加一个延迟或使用 block() (不推荐在生产环境使用)
        // userMono.block(); // 阻塞并获取结果,会失去异步的意义
    }
}

总结与如何选择

方法 优点 缺点 适用场景
HttpURLConnection JDK 内置,无依赖 代码繁琐,功能弱 简单脚本、小型项目、不想引入第三方库时
Apache HttpClient 功能强大,稳定,成熟 配置复杂,依赖较大 需要高级功能(如连接池、重试)的企业级应用
OkHttp API 简洁,性能高,流行 需要引入第三方库 Java 应用、Android 应用,是当前最通用的选择之一
Spring RestTemplate 与 Spring 无缝集成,方便 已不推荐,同步阻塞 旧版 Spring Boot 项目 (2.x)
Spring WebClient 现代,异步,高性能 学习曲线陡峭,仅限 Spring 新版 Spring Boot 项目 (3.x),需要高并发、异步性能的场景

选择建议:

  • 新项目,非 Spring 环境:首选 OkHttp,它在易用性、性能和流行度之间取得了很好的平衡。
  • 新项目,Spring Boot 3.x 环境:首选 WebClient,拥抱现代技术栈,利用其异步优势。
  • 旧项目,Spring Boot 2.x 环境:继续使用 RestTemplate,它依然稳定可靠。
  • 需要非常复杂的企业级功能:考虑 Apache HttpClient
  • 学习或简单任务:可以从 HttpURLConnection 开始,理解其原理。
分享:
扫描分享到社交APP
上一篇
下一篇