Java 调用 HTTP 接口的 7 种方式:全网最全指南

Java 调用 HTTP 接口的 7 种方式:全网最全指南

在开发过程中,调用 HTTP 接口是最常见的需求之一。本文将详细介绍 Java 中 7 种主流的调用 HTTP 接口的方式,包括每种工具的优缺点和完整代码实现。


1. 使用 RestTemplate

RestTemplate 是 Spring 提供的同步 HTTP 客户端,适用于传统项目。尽管从 Spring 5 开始被标记为过时,它仍然是许多开发者的首选。

示例代码

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.HttpMethod;
import org.springframework.http.MediaType;

public class RestTemplateExample {

    public static void main(String[] args) {
        // 接口地址
        String url = "https://your-api-url.com/target-method";

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("appId", "yourAppId");
        headers.add("timestamp", "yourTimestamp");
        headers.add("random", "yourRandom");
        headers.add("msgDigest", "yourMsgDigest");

        // 设置请求体
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;

        // 构造请求
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        // 输出响应结果
        System.out.println("Response: " + response.getBody());
    }
}

优缺点

  • 优点: 简单易用,适合快速开发。
  • 缺点: 已过时,不推荐用于新项目。

2. 使用 WebClient

WebClient 是 Spring 5 引入的现代化 HTTP 客户端,支持同步和异步调用。

示例代码

import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

public class WebClientExample {

    public static void main(String[] args) {
        // 创建 WebClient
        WebClient webClient = WebClient.builder()
                .baseUrl("https://your-api-url.com")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader("appId", "yourAppId")
                .defaultHeader("timestamp", "yourTimestamp")
                .defaultHeader("random", "yourRandom")
                .defaultHeader("msgDigest", "yourMsgDigest")
                .build();

        // 设置请求体
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;

        // 发送请求
        String response = webClient.post()
                .uri("/target-method")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .block(); // 同步调用

        // 输出响应结果
        System.out.println("Response: " + response);
    }
}

优缺点

  • 优点: 支持响应式编程,功能强大。
  • 缺点: API 较复杂,学习曲线较高。

3. 使用 OkHttp

OkHttp 是一个轻量级、高性能的 HTTP 客户端,支持同步和异步调用。

示例代码

import okhttp3.*;

public class OkHttpExample {

    public static void main(String[] args) throws Exception {
        // 创建 OkHttp 客户端
        OkHttpClient client = new OkHttpClient();

        // 设置请求体
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;

        // 构造请求
        Request request = new Request.Builder()
                .url("https://your-api-url.com/target-method")
                .post(RequestBody.create(requestBody, MediaType.parse("application/json")))
                .addHeader("appId", "yourAppId")
                .addHeader("timestamp", "yourTimestamp")
                .addHeader("random", "yourRandom")
                .addHeader("msgDigest", "yourMsgDigest")
                .build();

        // 发送请求
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println("Response: " + response.body().string());
            } else {
                System.err.println("Request failed: " + response.code());
            }
        }
    }
}

优缺点

  • 优点: 高性能,支持异步调用。
  • 缺点: 需要手动管理连接,代码量较多。

4. 使用 Apache HttpClient

Apache HttpClient 是一个功能强大且稳定的 HTTP 客户端,适合需要复杂功能(如代理、认证、多线程支持)的场景。

示例代码

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientExample {

    public static void main(String[] args) throws Exception {
        // 创建 HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 设置请求地址
        String url = "https://your-api-url.com/target-method";
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("appId", "yourAppId");
        httpPost.setHeader("timestamp", "yourTimestamp");
        httpPost.setHeader("random", "yourRandom");
        httpPost.setHeader("msgDigest", "yourMsgDigest");

        // 设置请求体
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;
        httpPost.setEntity(new StringEntity(requestBody));

        // 发送请求
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            String responseString = EntityUtils.toString(response.getEntity());
            System.out.println("Response: " + responseString);
        }
    }
}

优缺点

  • 优点: 功能强大,支持多线程、代理、连接池等。
  • 缺点: API 较为复杂,代码量较多。

5. 使用 Retrofit

Retrofit 是基于 OkHttp 的类型安全 HTTP 客户端,适合优雅地调用 REST API。

示例代码

定义接口
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public interface ApiService {

    @POST("/target-method")
    @Headers({
        "Content-Type: application/json",
        "appId: yourAppId",
        "timestamp: yourTimestamp",
        "random: yourRandom",
        "msgDigest: yourMsgDigest"
    })
    Call<String> createCz(@Body String requestBody);
}
调用服务
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.Call;
import retrofit2.Response;

public class RetrofitExample {

    public static void main(String[] args) throws Exception {
        // 创建 Retrofit 实例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://your-api-url.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        // 创建接口实例
        ApiService apiService = retrofit.create(ApiService.class);

        // 构造请求体
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;

        // 调用接口
        Call<String> call = apiService.createCz(requestBody);
        Response<String> response = call.execute();
        if (response.isSuccessful()) {
            System.out.println("Response: " + response.body());
        } else {
            System.err.println("Request failed: " + response.code());
        }
    }
}

优缺点

  • 优点: 注解式调用,简洁高效,自动处理 JSON。
  • 缺点: 适合中小型项目,不适合复杂场景。

6. 使用 HttpURLConnection

HttpURLConnection 是 Java 自带的原生 HTTP 客户端,适合不想引入外部依赖的小型项目。

示例代码

import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionExample {

    public static void main(String[] args) throws Exception {
        // 设置请求地址
        URL url = new URL("https://your-api-url.com/target-method");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法和属性
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("appId", "yourAppId");
        connection.setRequestProperty("timestamp", "yourTimestamp");
        connection.setRequestProperty("random", "yourRandom");
        connection.setRequestProperty("msgDigest", "yourMsgDigest");
        connection.setDoOutput(true);

        // 设置请求体
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;

        try (OutputStream os = connection.getOutputStream()) {
            os.write(requestBody.getBytes());
            os.flush();
        }

        // 获取响应
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                System.out.println("Response: " + response.toString());
            }
        } else {
            System.err.println("Request failed: " + responseCode);
        }
    }
}

优缺点

  • 优点: 无需额外依赖,适合简单场景。
  • 缺点: API 使用繁琐,功能有限。

7. 使用 OpenFeign

OpenFeign 是 Spring Cloud 提供的声明式 HTTP 客户端,适用于微服务间的接口调用。

示例代码

Feign 客户端接口

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

@FeignClient(name = "czClient", url = "https://your-api-url.com")
public interface CzClient {
    @PostMapping(value = "/target-method")
    String createCz(
        @RequestHeader("appId") String appId,
        @RequestHeader("timestamp") String timestamp,
        @RequestHeader("random") String random,
        @RequestHeader("msgDigest") String msgDigest,
        @RequestBody String requestBody
    );
}

服务调用逻辑

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CzService {

    @Autowired
    private CzClient czClient;

    public void callCzApi() {
        String response = czClient.createCz(
            "yourAppId",
            "yourTimestamp",
            "yourRandom",
            "yourMsgDigest",
            """
                {
                    "fileName": "yourFileName",
                    "fileSize": yourFileSize,
                    "dataType": "yourDataType",
                    "certificate": "yourCertificate",
                    "deposit": "yourDeposit",
                    "fileHash": "yourFileHash",
                    "userId": "yourUserId",
                    "appId": "yourAppId"
                }
            """
        );

        System.out.println("Response: " + response);
    }
}

优缺点

  • 优点: 声明式调用,集成 Spring 生态。
  • 缺点: 依赖 Spring Cloud,不适用于非 Spring 项目。

总结

工具 适用场景 优点 缺点
RestTemplate 简单的同步调用 简单易用 已过时,不推荐新项目使用
WebClient 高性能异步调用、响应式场景 支持异步与响应式调用 API 较复杂
OkHttp 性能要求高的小型项目 轻量高效,支持异步调用 需要手动管理,代码量较多
Apache HttpClient 复杂场景,如代理、多线程、认证等 功能强大,稳定性高 API 较复杂
Retrofit 注解式调用 REST API 简洁高效,自动处理 JSON 适合中小型项目,不适合复杂场景
HttpURLConnection 极简场景,无需额外依赖 内置支持,无需依赖外部库 使用复杂,功能有限
OpenFeign 微服务间的接口调用 声明式调用,集成 Spring 生态 依赖 Spring Cloud,不适用于非 Spring 项目

你可能感兴趣的:(Java 调用 HTTP 接口的 7 种方式:全网最全指南)