已更新 2025年3月26日
如何使用 HTTP 請求標頭
This article was translated from English: Does it need improvement?
TranslatedView the article in English
HTTP 請求標頭是由客戶端發送的一段元數據(例如網頁瀏覽器或 API 客戶端)在發送 HTTP 請求時到伺服器。標頭提供有關請求的額外信息,例如身份驗證詳細信息、內容類型、用戶代理等。
此功能在將 URL 轉換為 PDF 時使用,允許您在發出請求時提供 HTTP 標頭資訊。
開始使用 IronPDF
立即在您的專案中使用IronPDF,並享受免費試用。
How to use HTTP Request Header
- Download IronPDF from NuGet
- Prepare the HTTP request headers as a C# dictionary
- Assign the dictionary to the HttpRequestHeaders property
- Render the URL to PDF using the
RenderUrlAsPdf
method - Save the PDF as a file or export it as bytes
使用 HTTP 請求標頭範例
在使用 HttpRequestHeaders 屬性設置 HTTP 請求標頭之前,首先設計一個合適的 HTTP 請求標頭物件。 在渲染過程中,此標頭將包含在發送給伺服器的 URL 請求中。 作為範例,我們將使用httpbin.org,是一個網站,可協助顯示請求標頭。
:path=/static-assets/pdf/content-code-examples/how-to/http-request-header.cs
using IronPdf;
using System.Collections.Generic;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
{ "Authorization", "Bearer test-token-123" }
};
// Render PDF from authenticated page
var pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer");
pdf.SaveAs("output.pdf");
常見的 HTTP 請求標頭
- 授权:发送身份验证凭据(Bearer token, Basic auth, 等。)
- Content-Type:定義請求正文的格式(例如,application/json)
- Accept:指定預期的響應格式(例如,text/html、application/json)
- User-Agent:識別發出請求的客戶端(瀏覽器、API 客戶端等。)
- 引用頁:表示鏈接到當前請求的頁面
- Cookie: 發送 Cookie 用於會話追蹤