Java 调用 HTTP 接口的 7 种方式示例代码(全网最全指南)

 更新时间:2025年02月14日 09:56:29   作者:愤怒的代码  
在开发过程中,调用 HTTP 接口是最常见的需求之一,本文将详细介绍 Java 中 7 种主流的调用 HTTP 接口的方式,包括每种工具的优缺点和完整代码实现,感兴趣的朋友一起看看吧

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 种方式:全网最全指南的文章就介绍到这了,更多相关Java 调用 HTTP 接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringIntegration消息路由之Router的条件路由与过滤功能

    SpringIntegration消息路由之Router的条件路由与过滤功能

    本文详细介绍了Router的基础概念、条件路由实现、基于消息头的路由、动态路由与路由表、消息过滤与选择性路由以及错误处理与路由等方面的内容,提高了系统的可维护性和可扩展性,感兴趣的朋友一起看看吧
    2025-04-04
  • Java判断字符串是否是有效的括号(实例详解)

    Java判断字符串是否是有效的括号(实例详解)

    给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效,有效字符串需要满足:左括号必须用相同类型的右括号闭合,这篇文章主要介绍了Java判断字符串是否是有效的括号,需要的朋友可以参考下
    2023-10-10
  • Spring@Autowired与@Resource的区别有哪些

    Spring@Autowired与@Resource的区别有哪些

    这篇文章主要为大家详细介绍了@Autowired与@Resource的区别,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-02-02
  • Spring @Value如何通过${}、#{}注入不同类型的值

    Spring @Value如何通过${}、#{}注入不同类型的值

    这篇文章主要介绍了Spring @Value如何通过${}、#{}注入不同类型的值问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • Spring实现拥有者权限验证的方法示例

    Spring实现拥有者权限验证的方法示例

    这篇文章主要介绍了Spring实现拥有者权限验证的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • Java判断一个实体是不是空的简单方法

    Java判断一个实体是不是空的简单方法

    这篇文章主要给大家介绍了关于Java判断一个实体是不是空的简单方法,实际项目中我们会有很多地方需要判空校验,文中给出了详细的示例代码,需要的朋友可以参考下
    2023-07-07
  • java实现图片水平和垂直翻转效果

    java实现图片水平和垂直翻转效果

    这篇文章主要为大家详细介绍了java实现图片水平和垂直翻转效果,图片旋转的灵活运用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01
  • Java对象初始化过程代码块和构造器的调用顺序

    Java对象初始化过程代码块和构造器的调用顺序

    这篇文章主要介绍了Java对象初始化过程代码块和构造器的调用顺序,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-08-08
  • Java类继承关系中的初始化顺序实例详解

    Java类继承关系中的初始化顺序实例详解

    这篇文章主要介绍了Java类继承关系中的初始化顺序,结合实例形式详细对比分析了Java非继承关系中的初始化与继承关系中的初始化相关原理与操作技巧,需要的朋友可以参考下
    2019-09-09
  • springboot整合shardingjdbc实现分库分表最简单demo

    springboot整合shardingjdbc实现分库分表最简单demo

    我们知道分库分表是针对某些数据量持续大幅增长的表,比如用户表、订单表等,而不是一刀切将全部表都做分片,这篇文章主要介绍了springboot整合shardingjdbc实现分库分表最简单demo,需要的朋友可以参考下
    2021-06-06

最新评论