跳過到頁腳內容
JAVA 幫助

OkHttp Java:HTTP 請求簡化

在現代的 Java 開發中,高效處理 HTTP 請求對於構建強大的應用程式至關重要,特別是依賴於 Web 服務和 API 的應用程式。OkHttp 是一個功能強大的 Java 和 Kotlin HTTP/HTTP/2 客戶端,由於其性能、易用性和先進功能而成為流行的選擇。

本文提供了 OkHttp 的綜合指南,涵蓋其主要功能、安裝和常見的用例。

什麼是 OkHttp?

OkHttp 是一個多功能的開源 Java 庫,用於處理 HTTP 請求,提供豐富的功能集合,能夠無縫集成到您的應用程式中。 通過其直觀的 API,創建新請求或執行簡單的 POST 請求就像使用查詢參數和字符串 URL 配置新的請求構建器一樣簡單。

此外,OkHttp 促進了有效的響應處理,提供對響應正文、響應標頭的訪問,甚至支持響應緩存來優化網絡流量並減少服務器可用性問題。 無論您是在進行同步還是異步調用,OkHttp 的連接池技術都能確保最佳性能,即使在處理多個 IP 地址時也是如此。

OkHttp Java(開發者如何工作):圖1

對於習慣使用 Apache HTTP Client 的開發者來說,OkHttp 提供了一種更現代和高效的替代方案,具有更好的性能和靈活性。 其對於非同步調用和回調的支持使其成為需要響應性和可擴展性的應用程式的首選。

使用 OkHttp,管理許多 HTTP 客戶端和請求變得輕鬆自如,使開發者能夠專注於構建強大可靠的應用程式,而不影響性能或功能。

關鍵功能

OkHttp 的主要功能包括:

  • 同步和異步請求處理:OkHttp 允許同步(阻塞)和異步(非阻塞)操作。
  • 連接池技術(Connection pooling):重用 HTTP 連接以最小化客戶端連接問題並提高性能。
  • 透明 GZIP 壓縮:減小 HTTP 響應的大小,節省帶寬並加速數據傳輸。
  • 緩存:支持響應緩存,減少重複的網絡請求。
  • HTTP/2 支持:通過允許多個請求和響應在單個連接上多路複用來提高性能。
  • 超時和重試機制:提供精細的連接和讀取超時控制,以及失敗請求的重試機制。

安裝 OkHttp

要在您的 Java 項目中開始使用 OkHttp,您需要將其依賴項添加到構建配置中。 如果您使用 Maven,請將以下依賴項添加到您的 pom.xml 文件中:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>5.0.0-alpha.14</version>
</dependency>
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>5.0.0-alpha.14</version>
</dependency>
XML

對於 Gradle,將這行添加到您的 build.gradle 文件中:

implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.14'

請確保在 Maven Central 或 GitHub 上檢查最新版本。

基本用法

創建 OkHttpClient

OkHttpClient 類是執行 HTTP 請求的主要入口點。 建議創建一個單一的 OkHttpClient 實例並在整個應用程式中重複使用,以便利用連接池技術。

import okhttp3.OkHttpClient;

OkHttpClient client = new OkHttpClient();
import okhttp3.OkHttpClient;

OkHttpClient client = new OkHttpClient();
JAVA

進行 GET 請求

要進行一個簡單的 GET 請求,您需要創建一個 Request 對象並使用 OkHttpClient 執行它。

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class OkHttpExample {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        // Create a request specifying the URL
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Execute the request and handle the response
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) { // Check if the response was successful
                System.out.println(response.body().string()); // Print the response body
            } else {
                System.err.println("Request failed: " + response.code()); // Print error code
            }
        } catch (IOException e) {
            e.printStackTrace(); // Handle exceptions
        }
    }
}
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class OkHttpExample {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        // Create a request specifying the URL
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Execute the request and handle the response
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) { // Check if the response was successful
                System.out.println(response.body().string()); // Print the response body
            } else {
                System.err.println("Request failed: " + response.code()); // Print error code
            }
        } catch (IOException e) {
            e.printStackTrace(); // Handle exceptions
        }
    }
}
JAVA

OkHttp Java(開發者如何工作):圖2

進行 POST 請求

對於 POST 請求,您需要包含一個請求正文並返回響應。 OkHttp 提供了 RequestBody 類來處理這個。

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;

public class OkHttpExample {
    // Define the JSON media type
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        // JSON data to be sent
        String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";

        // Create request body with JSON data
        RequestBody body = RequestBody.create(json, JSON);

        // Build the POST request
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts")
                .post(body)
                .build();

        // Execute the request and handle the response
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) { // Check if the response was successful
                System.out.println(response.body().string()); // Print the response body
            } else {
                System.err.println("Request failed: " + response.code()); // Print error code
            }
        } catch (IOException e) {
            e.printStackTrace(); // Handle exceptions
        }
    }
}
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;

public class OkHttpExample {
    // Define the JSON media type
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        // JSON data to be sent
        String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";

        // Create request body with JSON data
        RequestBody body = RequestBody.create(json, JSON);

        // Build the POST request
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts")
                .post(body)
                .build();

        // Execute the request and handle the response
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) { // Check if the response was successful
                System.out.println(response.body().string()); // Print the response body
            } else {
                System.err.println("Request failed: " + response.code()); // Print error code
            }
        } catch (IOException e) {
            e.printStackTrace(); // Handle exceptions
        }
    }
}
JAVA

OkHttp Java(開發者如何工作):圖3

異步請求

異步請求是通過回調處理的,允許您的應用程式在等待響應時保持響應狀態。

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class OkHttpExample {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        // Create a request specifying the URL
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Enqueue the request to be executed asynchronously
        client.newCall(request).enqueue(new Callback() {

            // Handle failure of the request
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace(); // Handle exceptions
            }

            // Handle successful response
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) { // Check if the response was successful
                    System.out.println(response.body().string()); // Print the response body
                } else {
                    System.err.println("Request failed: " + response.code()); // Print error code
                }
            }
        });
    }
}
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class OkHttpExample {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        // Create a request specifying the URL
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Enqueue the request to be executed asynchronously
        client.newCall(request).enqueue(new Callback() {

            // Handle failure of the request
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace(); // Handle exceptions
            }

            // Handle successful response
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) { // Check if the response was successful
                    System.out.println(response.body().string()); // Print the response body
                } else {
                    System.err.println("Request failed: " + response.code()); // Print error code
                }
            }
        });
    }
}
JAVA

高級功能

攔截器(Interceptors)

攔截器是一個強大的功能,允許您檢查、修改或重試請求和響應。 它們可用於日誌記錄、添加標頭或處理認證。

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class OkHttpExample {
    public static void main(String[] args) {
        // Add an interceptor for modifying requests
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        // Modify the request to add the authorization header
                        Request request = chain.request().newBuilder()
                                .addHeader("Authorization", "Bearer your_token_here")
                                .build();
                        return chain.proceed(request);
                    }
                })
                .build();

        // Create a request specifying the URL
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Execute the request and handle the response
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) { // Check if the response was successful
                System.out.println(response.body().string()); // Print the response body
            } else {
                System.err.println("Request failed: " + response.code()); // Print error code
            }
        } catch (IOException e) {
            e.printStackTrace(); // Handle exceptions
        }
    }
}
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class OkHttpExample {
    public static void main(String[] args) {
        // Add an interceptor for modifying requests
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        // Modify the request to add the authorization header
                        Request request = chain.request().newBuilder()
                                .addHeader("Authorization", "Bearer your_token_here")
                                .build();
                        return chain.proceed(request);
                    }
                })
                .build();

        // Create a request specifying the URL
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Execute the request and handle the response
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) { // Check if the response was successful
                System.out.println(response.body().string()); // Print the response body
            } else {
                System.err.println("Request failed: " + response.code()); // Print error code
            }
        } catch (IOException e) {
            e.printStackTrace(); // Handle exceptions
        }
    }
}
JAVA

處理超時

OkHttp 提供了設置 HTTP 請求自己的不同階段的超時方法。

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkHttpExample {
    public static void main(String[] args) {
        // Configure timeouts for connections, writes, and reads
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();

        // Create a request specifying the URL
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Execute the request and handle the response
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) { // Check if the response was successful
                System.out.println(response.body().string()); // Print the response body
            } else {
                System.err.println("Request failed: " + response.code()); // Print error code
            }
        } catch (IOException e) {
            e.printStackTrace(); // Handle exceptions
        }
    }
}
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkHttpExample {
    public static void main(String[] args) {
        // Configure timeouts for connections, writes, and reads
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();

        // Create a request specifying the URL
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Execute the request and handle the response
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) { // Check if the response was successful
                System.out.println(response.body().string()); // Print the response body
            } else {
                System.err.println("Request failed: " + response.code()); // Print error code
            }
        } catch (IOException e) {
            e.printStackTrace(); // Handle exceptions
        }
    }
}
JAVA

緩存響應

OkHttp 可以緩存響應以減少請求延遲並提高性能。 這需要設置緩存目錄和大小。

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.File;
import java.io.IOException;

public class OkHttpExample {
    public static void main(String[] args) {
        // Define the cache directory and size
        File cacheDirectory = new File("cacheDirectory");
        Cache cache = new Cache(cacheDirectory, 10 * 1024 * 1024); // 10 MB cache

        // Build OkHttpClient with caching capability
        OkHttpClient client = new OkHttpClient.Builder()
                .cache(cache)
                .build();

        // Create a request specifying the URL
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Execute the request and handle the response
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) { // Check if the response was successful
                System.out.println(response.body().string()); // Print the response body
            } else {
                System.err.println("Request failed: " + response.code()); // Print error code
            }
        } catch (IOException e) {
            e.printStackTrace(); // Handle exceptions
        }
    }
}
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.File;
import java.io.IOException;

public class OkHttpExample {
    public static void main(String[] args) {
        // Define the cache directory and size
        File cacheDirectory = new File("cacheDirectory");
        Cache cache = new Cache(cacheDirectory, 10 * 1024 * 1024); // 10 MB cache

        // Build OkHttpClient with caching capability
        OkHttpClient client = new OkHttpClient.Builder()
                .cache(cache)
                .build();

        // Create a request specifying the URL
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        // Execute the request and handle the response
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) { // Check if the response was successful
                System.out.println(response.body().string()); // Print the response body
            } else {
                System.err.println("Request failed: " + response.code()); // Print error code
            }
        } catch (IOException e) {
            e.printStackTrace(); // Handle exceptions
        }
    }
}
JAVA

與 Java 中的 IronPDF 集成

結合 OkHttp 和 IronPDF 的功能使 Java 開發者能夠從 Web 獲取數據並將其轉換為 PDF。 OkHttp 是一個強大的 HTTP 客戶端,能夠處理網絡請求,而 IronPDF 是一個功能強大的庫,用於從各種來源生成 PDF。

IronPDF - 概述

IronPDF for Java 是一個設計用於簡化 Java 應用程式內 PDF 生成的綜合庫。 利用其直觀的 API,開發者可以輕鬆地從各種數據源(包括 HTML、圖像和文本)創建、操作和渲染 PDF 文檔。

支持 PDF 加密、數字簽名和交互式表單填寫等高級功能,使 IronPDF 能夠滿足開發者特定要求的專業級 PDF。 其無縫集成和豐富的文檔使其成為希望通過強大的 PDF 生成功能提升其應用程式的 Java 開發者的首選解決方案。

OkHttp Java(開發者如何工作):圖4

設置依賴項

首先,將必要的依賴項添加到您的 pom.xml(對於 Maven)檔案或 build.gradle(對於 Gradle)檔案中。

Maven

<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>2024.3.1</version>
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>2024.3.1</version>
</dependency>
XML

Gradle

implementation 'com.ironsoftware:ironpdf:2024.3.1'

整合 OkHttp 和 IronPDF

現在,讓我們將這兩種功能結合起來:使用 OkHttp 獲取 HTML 內容並使用 IronPDF 生成 PDF。

import com.ironsoftware.ironpdf.PdfDocument;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.nio.file.Paths;

public class OkHttpToPdf {
    private final OkHttpClient client = new OkHttpClient(); // Initialize the OkHttpClient

    // Method to fetch HTML content from a given URL
    public String fetchHtml(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        // Execute the request and return the response body as a string
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return response.body().string();
        }
    }

    // Method to generate a PDF from a URL
    public void generatePdfFromUrl(String url, String outputFilePath) {
        try {
            String htmlContent = fetchHtml(url); // Fetch the HTML content
            PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlContent); // Render HTML as PDF
            pdf.saveAs(Paths.get(outputFilePath)); // Save the PDF to the specified path
            System.out.println("PDF generated successfully at " + outputFilePath);
        } catch (IOException e) {
            System.err.println("Failed to fetch HTML content: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("Failed to generate PDF: " + e.getMessage());
        }
    }

    // Main method to demonstrate fetching HTML and generating a PDF
    public static void main(String[] args) {
        OkHttpToPdf converter = new OkHttpToPdf(); // Create an instance of OkHttpToPdf
        converter.generatePdfFromUrl("https://ironpdf.com/java", "website.pdf"); // Fetch HTML and generate PDF
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.nio.file.Paths;

public class OkHttpToPdf {
    private final OkHttpClient client = new OkHttpClient(); // Initialize the OkHttpClient

    // Method to fetch HTML content from a given URL
    public String fetchHtml(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        // Execute the request and return the response body as a string
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return response.body().string();
        }
    }

    // Method to generate a PDF from a URL
    public void generatePdfFromUrl(String url, String outputFilePath) {
        try {
            String htmlContent = fetchHtml(url); // Fetch the HTML content
            PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlContent); // Render HTML as PDF
            pdf.saveAs(Paths.get(outputFilePath)); // Save the PDF to the specified path
            System.out.println("PDF generated successfully at " + outputFilePath);
        } catch (IOException e) {
            System.err.println("Failed to fetch HTML content: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("Failed to generate PDF: " + e.getMessage());
        }
    }

    // Main method to demonstrate fetching HTML and generating a PDF
    public static void main(String[] args) {
        OkHttpToPdf converter = new OkHttpToPdf(); // Create an instance of OkHttpToPdf
        converter.generatePdfFromUrl("https://ironpdf.com/java", "website.pdf"); // Fetch HTML and generate PDF
    }
}
JAVA

代碼解釋

以上代碼演示了如何使用 Java 中的 OkHttp 和 IronPDF 庫從 URL 獲取 HTML 內容並將其轉換為 PDF 文件:

  1. 導入語句:導入必要的庫,包括生成 PDF 的 IronPDF 和處理 HTTP 請求的 OkHttp。

  2. OkHttpClient 初始化:創建 OkHttpClient 的實例。

  3. fetchHtml 方法:該方法從指定的 URL 獲取 HTML 內容。

    • 構建一個使用提供的 URL 的請求。
    • 執行請求並獲得響應。
    • 如果響應不成功,則拋出 IOException
    • 將響應主體作為字符串返回。
  4. generatePdfFromUrl 方法:該方法從指定 URL 的 HTML 內容生成 PDF 並將其保存到指定文件路徑。

    • 使用 fetchHtml 方法獲取 HTML 內容。
    • 使用 IronPDF 將 HTML 內容渲染為 PDF。
    • 將 PDF 保存到指定文件路徑。
    • 包括對 HTML 獲取和 PDF 生成的適當錯誤處理。
  5. main 方法:這是程序的入口點。

    • 創建 OkHttpToPdf 的實例。
    • 使用指定的 URL 和輸出文件路徑調用 generatePdfFromUrl 方法。

輸出

使用 OkHttp 客戶端獲取 URL 數據後再利用 IronPDF 高效渲染轉換為 PDF,如下所示:

OkHttp Java(開發者如何工作):圖5

如需有關 IronPDF 的詳細信息,請訪問此IronPDF 文檔頁面。 Please also check this IronPDF Code Examples and IronPDF API Reference page for further utilizing IronPDF.

結論

OkHttp 是一個多才多藝且強大的 Java 和 Android HTTP 客戶端,簡化了網絡請求的過程。 憑藉對同步和異步操作、連接池技術、透明 GZIP 壓縮、緩存和 HTTP/2 的支持,OkHttp 客戶端適合於廣泛的使用情況。 通過將 OkHttp 集成到您的 Java 應用程式中,您可以提高其性能、可靠性和效率。

通過將 OkHttp 與 IronPDF 結合使用,您可以高效地獲取來自 Web 來源的 HTML 內容並將其轉換為 PDF 文檔。 此方法特別適用於需要生成報告、保存網頁或將 Web 內容轉換為離線文檔的應用程式。

在您的 Java 應用程式中發揮 IronPDF 的 PDF 生成潛力,使用< a href="trial-license">免費試用版,使您的項目前所未有地集成專業級 PDF 生成。 立即下載提升您的 PDF 生成體驗!

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。