IRONSOFTWAREHOME
JAVA 幫助

OkHttp Java:HTTP 請求簡化

Curtis Chau
Curtis Chau
Updated: 2026年4月21日

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

本文提供了OkHttp的全面指南,涵蓋其關鍵功能、安裝和常見用例。

什麼是OkHttp?

OkHttp是一個通用的開源Java程式庫,用於處理HTTP請求,提供了一整套功能,用於無縫整合到您的應用程式中。 憑藉其直觀的API,建立一個新請求或執行簡單的POST請求就像配置一個帶有查詢參數和字串URL的新請求建構器一樣簡單。

此外,OkHttp促進了高效的響應處理,提供對響應正文、響應標頭的存取,甚至支持響應快取,以優化網路流量,減少伺服器可用性問題。 不論您是進行同步還是異步呼叫,OkHttp的連接池確保了最佳性能,即使在處理多個IP地址時也是如此。

OkHttp Java (For Developers How It Works):圖1

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

借助OkHttp,管理眾多HTTP客戶端和請求變得輕而易舉,讓開發者能專注於構建強大且可靠的應用程式,而不妥協於性能或功能。

主要功能

OkHttp的主要功能包括:

  • 同步與異步請求處理: OkHttp允許同步(阻塞)和異步(非阻塞)操作。
  • 連接池: 重複使用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>
XML

對於Gradle,將這行新增到您的build.gradle檔案中:

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

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

基本用法

建立OkHttpClient

OkHttpClient類是執行HTTP請求的主要切入點。 建議建立一個OkHttpClient實例,並在整個應用程式中重複使用它,以充分利用連接池。

import okhttp3.OkHttpClient;

OkHttpClient client = new OkHttpClient();
Java

發送GET請求

要進行簡單的GET請求,您需要建立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
        }
    }
}
Java

OkHttp Java (For Developers How It Works):圖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
        }
    }
}
Java

OkHttp Java (For Developers How It Works):圖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
                }
            }
        });
    }
}
Java

進階功能

攔截器

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

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
        }
    }
}
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
        }
    }
}
Java

將OkHttp與IronPDF整合到Java中

結合OkHttp和IronPDF的功能,使Java開發者能夠從網路上獲取資料並將其轉換為PDF文件。 OkHttp是一個用於處理網路請求的強大HTTP客戶端,而IronPDF是一個強大的生成PDF的程式庫。

IronPDF - 概述

IronPDF for Java是一個全面的程式庫,旨在簡化Java應用程式中的PDF生成。 利用其直觀的API,開發者可以輕鬆地從各種資料來源(包括HTML、圖片和文字)建立、操作和渲染PDF文件。

支援高級功能,如PDF加密、數位簽名和互動表單填寫,IronPDF使開發者能夠根據他們的具體要求生成專業級的PDF。 其無縫整合和廣泛的文件使其成為尋求增強其應用程式的Java開發者的理想解決方案。

OkHttp Java (For Developers How It Works):圖4

設置依賴項

首先,將必要的依賴項新增到您的build.gradle(對於Gradle)文件中。

Maven

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

Gradle

implementation 'com.ironsoftware:ironpdf:2024.3.1'
Text

整合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
    }
}
Java

程式碼解釋

上述程式碼演示了如何從一個URL抓取HTML內容,並使用Java中的OkHttp和IronPDF程式庫將其轉換為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 (For Developers How It Works):圖5

如需更多有關IronPDF的詳細資訊,請存取此IronPDF 文件頁面。 還請檢查此IronPDF程式碼範例IronPDF API參考頁面以進一步利用IronPDF。

結論

OkHttp是一個通用且強大的Java和Android HTTP客戶端,它簡化了進行網路請求的過程。 藉由其對同步和異步操作、連接池、透明GZIP壓縮、快取、以及HTTP/2的支持,OkHttp客戶端適合各種用例。 透過將OkHttp整合到您的Java應用程式中,您可以增強其性能、可靠性和效率。

透過將OkHttp與IronPDF整合,您可以有效地從Web來源獲取HTML內容並將其轉換為PDF文件。 這種方法對於需要生成報告、保存網頁或將Web內容轉換為離線文件的應用程式尤其有用。

利用IronPDF的免費試用解鎖您Java應用程式中的PDF生成潛力,實現專業級PDF生成的無縫整合。 立即下載並提升您的PDF生成體驗!

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...
Read More

Related Articles

Key in blue circle

立即免費取得 30 天試用金鑰

bullet_checked無需信用卡或建立帳號
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費 即時演示
Booking Badge related to IronPDF Product Demo

全球數百萬工程師的信任

Iron Software的客戶商標
獲取您的無義務諮詢
填寫以下表格或發送電子郵件至sales@ironsoftware.com
您的詳細資訊始終保持機密。
全球數百萬工程師的信任
Iron Software的客戶商標
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立