跳過到頁腳內容
JAVA 幫助

OkHttp Java:HTTP 請求簡化

在現代Java開發中,如何高效處理HTTP請求是建立穩健應用程式的關鍵,特別是那些依賴於網絡服務和API的應用程式。OkHttp是一個強大的HTTP和HTTP/2客戶端,適用於Java和Kotlin,由於其性能、易用性和高級功能而成為流行的選擇。

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

什麼是OkHttp?

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

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

OkHttp Java(為開發者而設計的運作方式):圖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>
<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請求,您需要創建一個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

高級功能

攔截器

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

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

將OkHttp與IronPDF整合在Java中

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

IronPDF - 概述

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

支持高級功能,如PDF加密、數位簽名和互動式表格填寫,IronPDF使開發者能夠根據其特定需求生成專業級的PDF。 其無縫整合和廣泛的文檔使其成為Java開發者提升其應用程式的首選方案,具備強大的PDF生成能力。

OkHttp Java(為開發者而設計的運作方式):圖4

設置相依性

首先,將必要的相依性添加到您的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

代碼解釋

上面的程式碼展示了如何使用OkHttp和IronPDF程式庫在Java中從URL提取HTML內容並將其轉換為PDF文件:

  1. 匯入語句: 匯入必要的程式庫,包括IronPDF進行PDF生成和OkHttp進行HTTP請求。

  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方法。

輸出

URL數據使用OkHttp客戶端提取,然後使用IronPDF有效地進行渲染轉換為PDF,如下所示:

OkHttp Java(為開發者而設計的運作方式):圖5

有關IronPDF的詳細資訊,請訪問此IronPDF文檔頁面。 請同時查看此IronPDF代碼示例IronPDF API引用頁面,以便進一步利用IronPDF。

結論

OkHttp是一個多功能且強大的HTTP客戶端,用於Java和Android,簡化了網絡請求的過程。 OkHttp的客戶端支持同步和異步操作、連接池、透明的GZIP壓縮、快取和HTTP/2,非常適合於廣泛的使用案例。 通過將OkHttp整合到您的Java應用程序中,您可以提高其性能、可靠性和效率。

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

使用IronPDF的免費試用解鎖Java應用程序中的PDF生成潛力,實現專業級PDF生成無縫集成到您的項目中。 立即下載並提升您的PDF生成體驗!

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

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

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

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

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me