欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java 調(diào)用 HTTP 接口的 7 種方式示例代碼(全網(wǎng)最全指南)

 更新時(shí)間:2025年02月14日 09:56:29   作者:憤怒的代碼  
在開發(fā)過程中,調(diào)用 HTTP 接口是最常見的需求之一,本文將詳細(xì)介紹 Java 中 7 種主流的調(diào)用 HTTP 接口的方式,包括每種工具的優(yōu)缺點(diǎn)和完整代碼實(shí)現(xiàn),感興趣的朋友一起看看吧

Java 調(diào)用 HTTP 接口的 7 種方式:全網(wǎng)最全指南

在開發(fā)過程中,調(diào)用 HTTP 接口是最常見的需求之一。本文將詳細(xì)介紹 Java 中 7 種主流的調(diào)用 HTTP 接口的方式,包括每種工具的優(yōu)缺點(diǎn)和完整代碼實(shí)現(xiàn)。

1. 使用 RestTemplate

RestTemplate 是 Spring 提供的同步 HTTP 客戶端,適用于傳統(tǒng)項(xiàng)目。盡管從 Spring 5 開始被標(biāo)記為過時(shí),它仍然是許多開發(fā)者的首選。

示例代碼

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";
        // 設(shè)置請(qǐng)求頭
        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");
        // 設(shè)置請(qǐng)求體
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;
        // 構(gòu)造請(qǐng)求
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
        // 發(fā)送請(qǐng)求
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        // 輸出響應(yīng)結(jié)果
        System.out.println("Response: " + response.getBody());
    }
}

優(yōu)缺點(diǎn)

  • 優(yōu)點(diǎn): 簡(jiǎn)單易用,適合快速開發(fā)。
  • 缺點(diǎn): 已過時(shí),不推薦用于新項(xiàng)目。

2. 使用 WebClient

WebClient 是 Spring 5 引入的現(xiàn)代化 HTTP 客戶端,支持同步和異步調(diào)用。

示例代碼

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) {
        // 創(chuàng)建 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();
        // 設(shè)置請(qǐng)求體
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;
        // 發(fā)送請(qǐng)求
        String response = webClient.post()
                .uri("/target-method")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .block(); // 同步調(diào)用
        // 輸出響應(yīng)結(jié)果
        System.out.println("Response: " + response);
    }
}

優(yōu)缺點(diǎn)

  • 優(yōu)點(diǎn): 支持響應(yīng)式編程,功能強(qiáng)大。
  • 缺點(diǎn): API 較復(fù)雜,學(xué)習(xí)曲線較高。

3. 使用 OkHttp

OkHttp 是一個(gè)輕量級(jí)、高性能的 HTTP 客戶端,支持同步和異步調(diào)用。

示例代碼

import okhttp3.*;
public class OkHttpExample {
    public static void main(String[] args) throws Exception {
        // 創(chuàng)建 OkHttp 客戶端
        OkHttpClient client = new OkHttpClient();
        // 設(shè)置請(qǐng)求體
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;
        // 構(gòu)造請(qǐng)求
        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();
        // 發(fā)送請(qǐng)求
        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());
            }
        }
    }
}

優(yōu)缺點(diǎn)

  • 優(yōu)點(diǎn): 高性能,支持異步調(diào)用。
  • 缺點(diǎn): 需要手動(dòng)管理連接,代碼量較多。

4. 使用 Apache HttpClient

Apache HttpClient 是一個(gè)功能強(qiáng)大且穩(wěn)定的 HTTP 客戶端,適合需要復(fù)雜功能(如代理、認(rèn)證、多線程支持)的場(chǎng)景。

示例代碼

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 {
        // 創(chuàng)建 HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 設(shè)置請(qǐng)求地址
        String url = "https://your-api-url.com/target-method";
        HttpPost httpPost = new HttpPost(url);
        // 設(shè)置請(qǐng)求頭
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("appId", "yourAppId");
        httpPost.setHeader("timestamp", "yourTimestamp");
        httpPost.setHeader("random", "yourRandom");
        httpPost.setHeader("msgDigest", "yourMsgDigest");
        // 設(shè)置請(qǐng)求體
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;
        httpPost.setEntity(new StringEntity(requestBody));
        // 發(fā)送請(qǐng)求
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            String responseString = EntityUtils.toString(response.getEntity());
            System.out.println("Response: " + responseString);
        }
    }
}

優(yōu)缺點(diǎn)

  • 優(yōu)點(diǎn): 功能強(qiáng)大,支持多線程、代理、連接池等。
  • 缺點(diǎn): API 較為復(fù)雜,代碼量較多。

5. 使用 Retrofit

Retrofit 是基于 OkHttp 的類型安全 HTTP 客戶端,適合優(yōu)雅地調(diào)用 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);
}

調(diào)用服務(wù)

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 {
        // 創(chuàng)建 Retrofit 實(shí)例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://your-api-url.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        // 創(chuàng)建接口實(shí)例
        ApiService apiService = retrofit.create(ApiService.class);
        // 構(gòu)造請(qǐng)求體
        String requestBody = """
            {
                "fileName": "yourFileName",
                "fileSize": yourFileSize,
                "dataType": "yourDataType",
                "certificate": "yourCertificate",
                "deposit": "yourDeposit",
                "fileHash": "yourFileHash",
                "userId": "yourUserId",
                "appId": "yourAppId"
            }
        """;
        // 調(diào)用接口
        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());
        }
    }
}

優(yōu)缺點(diǎn)

  • 優(yōu)點(diǎn): 注解式調(diào)用,簡(jiǎn)潔高效,自動(dòng)處理 JSON。
  • 缺點(diǎn): 適合中小型項(xiàng)目,不適合復(fù)雜場(chǎng)景。

6. 使用 HttpURLConnection

HttpURLConnection 是 Java 自帶的原生 HTTP 客戶端,適合不想引入外部依賴的小型項(xiàng)目。

示例代碼

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 {
        // 設(shè)置請(qǐng)求地址
        URL url = new URL("https://your-api-url.com/target-method");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 設(shè)置請(qǐng)求方法和屬性
        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);
        // 設(shè)置請(qǐng)求體
        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();
        }
        // 獲取響應(yīng)
        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);
        }
    }
}

優(yōu)缺點(diǎn)

  • 優(yōu)點(diǎn): 無需額外依賴,適合簡(jiǎn)單場(chǎng)景。
  • 缺點(diǎn): API 使用繁瑣,功能有限。

7. 使用 OpenFeign

OpenFeign 是 Spring Cloud 提供的聲明式 HTTP 客戶端,適用于微服務(wù)間的接口調(diào)用。

示例代碼

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

服務(wù)調(diào)用邏輯

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

優(yōu)缺點(diǎn)

  • 優(yōu)點(diǎn): 聲明式調(diào)用,集成 Spring 生態(tài)。
  • 缺點(diǎn): 依賴 Spring Cloud,不適用于非 Spring 項(xiàng)目。

總結(jié)

工具適用場(chǎng)景優(yōu)點(diǎn)缺點(diǎn)
RestTemplate簡(jiǎn)單的同步調(diào)用簡(jiǎn)單易用已過時(shí),不推薦新項(xiàng)目使用
WebClient高性能異步調(diào)用、響應(yīng)式場(chǎng)景支持異步與響應(yīng)式調(diào)用API 較復(fù)雜
OkHttp性能要求高的小型項(xiàng)目輕量高效,支持異步調(diào)用需要手動(dòng)管理,代碼量較多
Apache HttpClient復(fù)雜場(chǎng)景,如代理、多線程、認(rèn)證等功能強(qiáng)大,穩(wěn)定性高API 較復(fù)雜
Retrofit注解式調(diào)用 REST API簡(jiǎn)潔高效,自動(dòng)處理 JSON適合中小型項(xiàng)目,不適合復(fù)雜場(chǎng)景
HttpURLConnection極簡(jiǎn)場(chǎng)景,無需額外依賴內(nèi)置支持,無需依賴外部庫使用復(fù)雜,功能有限
OpenFeign微服務(wù)間的接口調(diào)用聲明式調(diào)用,集成 Spring 生態(tài)依賴 Spring Cloud,不適用于非 Spring 項(xiàng)目

到此這篇關(guān)于Java 調(diào)用 HTTP 接口的 7 種方式:全網(wǎng)最全指南的文章就介紹到這了,更多相關(guān)Java 調(diào)用 HTTP 接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springboot整合shardingjdbc實(shí)現(xiàn)分庫分表最簡(jiǎn)單demo

    springboot整合shardingjdbc實(shí)現(xiàn)分庫分表最簡(jiǎn)單demo

    我們知道分庫分表是針對(duì)某些數(shù)據(jù)量持續(xù)大幅增長(zhǎng)的表,比如用戶表、訂單表等,而不是一刀切將全部表都做分片,這篇文章主要介紹了springboot整合shardingjdbc實(shí)現(xiàn)分庫分表最簡(jiǎn)單demo,需要的朋友可以參考下
    2021-06-06
  • 最新評(píng)論