JAVA 帮助 OkHttp Java: HTTP 请求简化 Darrius Serrant 已更新:2026年1月18日 下载 IronPDF Maven 下载 JAR 下载 免费试用 LLM副本 LLM副本 将页面复制为 Markdown 格式,用于 LLMs 在 ChatGPT 中打开 向 ChatGPT 咨询此页面 在双子座打开 向 Gemini 询问此页面 在 Grok 中打开 向 Grok 询问此页面 打开困惑 向 Perplexity 询问有关此页面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 复制链接 电子邮件文章 在现代 Java 开发中,高效处理 HTTP 请求对于构建强大的应用程序至关重要,特别是那些依赖于 Web 服务和 API 的应用程序。OkHttp,一个强大的 Java 和 Kotlin 的 HTTP & HTTP/2 客户端,因其性能、易用性和高级功能而成为流行的选择。 本文提供了一个关于 OkHttp 的综合指南,涵盖其关键特性、安装以及常见使用案例。 什么是 OkHttp? OkHttp 是一个多功能的开源 Java 库,用于处理 HTTP 请求,提供了一套全面的功能以便于在您的应用程序中进行无缝集成。 由于其直观的 API,创建新的请求或执行简单的 POST 请求就像配置一个新的请求构建器并使用查询参数和字符串 URL 一样简单。 此外,OkHttp 促进了高效的响应处理,提供对响应体、响应头的访问,甚至支持响应缓存以优化网络流量并减少服务器可用性问题。 无论您是进行同步还是异步调用,OkHttp 的连接池确保最佳性能,甚至在处理多个 IP 地址时也不例外。 对于习惯使用 Apache HTTP 客户端的开发者来说,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 中心或 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 进行 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 异步请求 异步请求通过回调进行处理,允许您的应用程序在等待响应时保持响应性。 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 在 Java 中集成 OkHttp 和 IronPDF 结合 OkHttp 和 IronPDF 的能力可以使 Java 开发者从网络中获取数据并将其转换为 PDF。 OkHttp 是一个强大的 HTTP 客户端,用于处理网络请求,而 IronPDF 是一个从各种来源生成 PDF 的强大库。 IronPDF - 概述 IronPDF for Java 是一个综合库,设计旨在简化 Java 应用程序中的 PDF 生成。 利用其直观的 API,开发者可以轻松地从各种数据源创建、操作和渲染 PDF 文档,包括 HTML、图像和文本。 支持高级特性如 PDF 加密、数字签名和交互式表单填充,IronPDF 使开发者能够根据其特定需求生成专业级别的 PDF。 其无缝集成和广泛的文档使其成为寻求增强其应用程序以实现强大 PDF 生成能力的 Java 开发者的首选解决方案。 设置依赖项 首先,将必要的依赖项添加到您的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.导入语句:导入必要的库,包括用于生成 PDF 的IronPDF和用于 HTTP 请求的 OkHttp。 OkHttpClient 初始化:创建一个OkHttpClient实例。 fetchHtml方法:此方法从指定的URL获取HTML内容。 使用提供的 URL 构建请求。 执行请求并获取响应。 如果响应不成功,则抛出IOException。 将响应体作为字符串返回。 generatePdfFromUrl方法:此方法从指定URL的HTML内容生成PDF并保存到给定的文件路径。 使用fetchHtml方法获取HTML内容。 使用IronPDF将HTML内容渲染为PDF。 将 PDF 保存到指定的文件路径。 对 HTML 获取和 PDF 生成进行了适当的错误处理。 main方法:这是程序的入口点。 创建一个OkHttpToPdf实例。 调用generatePdfFromUrl方法,传入一个特定的URL和输出文件路径。 输出 URL 数据使用 OkHttp 客户端获取,然后使用 IronPDF 高效地将其呈现以便转换为 PDF,如下所示: 有关 IronPDF 的更多详细信息,请访问这个 IronPDF 文档 页面。 另外请查看此 IronPDF 代码示例 和 IronPDF API 参考 页面,以便进一步利用 IronPDF。 结论 OkHttp 是一个多功能且强大的 Java 和 Android HTTP 客户端,可简化网络请求的过程。 凭借其对同步和异步操作、连接池、透明的 GZIP 压缩、缓存和 HTTP/2 的支持,OkHttp 客户端非常适合广泛的用例。 通过将 OkHttp 集成到您的 Java 应用程序中,您可以提高其性能、可靠性和效率。 通过将 OkHttp 与 IronPDF 集成,您可以高效地从网络来源获取 HTML 内容并将其转换为 PDF 文档。 这种方法特别适用于需要生成报告、保存网页或将网页内容转换为离线文档的应用程序。 使用 IronPDF 的 免费试用 版释放您的 Java 应用程序中的 PDF 生成潜力,使专业级 PDF 生成与您的项目无缝集成。 立即下载,提升您的 PDF 生成体验! Darrius Serrant 立即与工程团队聊天 全栈软件工程师(WebOps) Darrius Serrant 拥有迈阿密大学的计算机科学学士学位,目前在 Iron Software 担任全栈 WebOps 市场工程师。从小就被编码吸引,他认为计算机既神秘又易于接触,使其成为创意和问题解决的理想媒介。在 Iron Software,Darrius 喜欢创造新事物,并简化复杂概念以使其更易理解。作为我们常驻的开发者之一,他还自愿教授学生,与下一代分享他的专业知识。对于 Darrius 来说,他的工作令人满意,因为它被重视并产生真正的影响。 相关文章 已更新2025年10月26日 Java 通过引用传递 (开发人员如何运作) 在 Java 编程语言中,参数传递总是通过值传递。当处理对象时,引用变量被值传递 阅读更多 已更新2026年1月18日 Java Scanner (开发人员如何运作) 在本文中,我们将深入了解 Java Scanner 类的工作原理,并通过示例探索其用法 阅读更多 已更新2026年1月18日 Java Printf (开发人员如何运作) 通过将 IronPDF 与 Java 的 printf 功能集成,可以通过准确的文本格式优化 PDF 输出 阅读更多 Apache Commons IO: Java I/O 实用工具Gson for Java: 将对象转换为 JSON