java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java 调用 HTTP 接口

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

作者:愤怒的代码

在开发过程中,调用 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);
    }
}

优缺点

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);
        }
    }
}

优缺点

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());
        }
    }
}

优缺点

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);
        }
    }
}

优缺点

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);
    }
}

优缺点

总结

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

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

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