在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
RestSharp是一個受歡迎的開源 .NET 函式庫,用於在 C# 中發送 HTTP 請求。 它簡化了使用 RESTful API 的過程,提供了一種簡單而靈活的方法來與網絡服務進行通信。 在本文中,我們將探討的重要功能RestSharp和IronPDF並展示如何提取數據和生成 PDF。
在現代的多層應用程式中,不同的服務經常需要相互通信,而RestSharp通過封裝所有的複雜性提供了一種簡單且高效的方法。 這大大簡化了軟體開發過程。
RestSharp 可用作NuGet在您的C#專案中可以安裝的套件。 您可以使用 NuGet 套件管理器控制台來完成此操作,或者使用Visual StudioNuGet 套件管理器 UI。
Install-Package RestSharp
讓我們從一個使用 RestSharp 對 RESTful API 進行 GET 請求的簡單例子開始。假設我們想從一個返回用戶數據的公共 ASP.NET core API 中檢索信息:
using RestSharp;
namespace rest_sharp_demo;
class Program
{
static void Main()
{
// Create a RestClient instance
var baseUrl = "https://jsonplaceholder.typicode.com/users";
RestClientOptions options = new RestClientOptions(baseUrl)
{UseDefaultCredentials = true};
var client = new RestClient(options);
// Create a RestRequest for the GET method
var request = new RestRequest();
// Execute the request and get the response
var response = client.Get(request);
// Check if the request was successful
if (response.IsSuccessful)
{
// Output the response body content
Console.WriteLine(response.Content);
}
else
{
// Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
public void LogData(string msg)
{
Console.WriteLine(msg)
}
}
using RestSharp;
namespace rest_sharp_demo;
class Program
{
static void Main()
{
// Create a RestClient instance
var baseUrl = "https://jsonplaceholder.typicode.com/users";
RestClientOptions options = new RestClientOptions(baseUrl)
{UseDefaultCredentials = true};
var client = new RestClient(options);
// Create a RestRequest for the GET method
var request = new RestRequest();
// Execute the request and get the response
var response = client.Get(request);
// Check if the request was successful
if (response.IsSuccessful)
{
// Output the response body content
Console.WriteLine(response.Content);
}
else
{
// Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
public void LogData(string msg)
{
Console.WriteLine(msg)
}
}
Imports RestSharp
Namespace rest_sharp_demo
Friend Class Program
Shared Sub Main()
' Create a RestClient instance
Dim baseUrl = "https://jsonplaceholder.typicode.com/users"
Dim options As New RestClientOptions(baseUrl) With {.UseDefaultCredentials = True}
Dim client = New RestClient(options)
' Create a RestRequest for the GET method
Dim request = New RestRequest()
' Execute the request and get the response
Dim response = client.Get(request)
' Check if the request was successful
If response.IsSuccessful Then
' Output the response body content
Console.WriteLine(response.Content)
Else
' Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}")
End If
End Sub
Public Sub LogData(ByVal msg As String)
Console.WriteLine(msg)
End Sub
End Class
End Namespace
RestSharp 也支援使用非同步 API 方法的非同步請求和響應。
RestSharp 提供了將回應內容反序列化為 C# 物件的便利方法。 讓我們擴展範例以將 JSON 回應數據反序列化為用戶物件列表:
// Deserialize JSON response into a list of User objects
var users = JsonSerializer.Deserialize<List<User>>(response.Content);
// Output user information
foreach (var user in users)
{
Console.WriteLine($"User ID: {user.Id}, Name: {user.Name}, Email:{user.Email}");
}
// Deserialize JSON response into a list of User objects
var users = JsonSerializer.Deserialize<List<User>>(response.Content);
// Output user information
foreach (var user in users)
{
Console.WriteLine($"User ID: {user.Id}, Name: {user.Name}, Email:{user.Email}");
}
' Deserialize JSON response into a list of User objects
Dim users = JsonSerializer.Deserialize(Of List(Of User))(response.Content)
' Output user information
For Each user In users
Console.WriteLine($"User ID: {user.Id}, Name: {user.Name}, Email:{user.Email}")
Next user
在此示例中,我們定義了一個 User
類別,其屬性對應於 JSON 字段。 我們使用了 System.Text.Json.Serialization
命名空間中的 JsonSerializer.Deserialize
。
public class User
{
[JsonPropertyName("company")]public Company Company { get; set; }
[JsonPropertyName("id")]public int Id { get; set; }
[JsonPropertyName("phone")]public string Phone { get; set; }
[JsonPropertyName("website")]public string Website { get; set; }
[JsonPropertyName("name")]public string Name { get; set; }
[JsonPropertyName("username")]public string Username { get; set; }
[JsonPropertyName("email")]public string Email { get; set; }
[JsonPropertyName("address")]public Address Address { get; set; }
}
public class User
{
[JsonPropertyName("company")]public Company Company { get; set; }
[JsonPropertyName("id")]public int Id { get; set; }
[JsonPropertyName("phone")]public string Phone { get; set; }
[JsonPropertyName("website")]public string Website { get; set; }
[JsonPropertyName("name")]public string Name { get; set; }
[JsonPropertyName("username")]public string Username { get; set; }
[JsonPropertyName("email")]public string Email { get; set; }
[JsonPropertyName("address")]public Address Address { get; set; }
}
Public Class User
<JsonPropertyName("company")>
Public Property Company() As Company
<JsonPropertyName("id")>
Public Property Id() As Integer
<JsonPropertyName("phone")>
Public Property Phone() As String
<JsonPropertyName("website")>
Public Property Website() As String
<JsonPropertyName("name")>
Public Property Name() As String
<JsonPropertyName("username")>
Public Property Username() As String
<JsonPropertyName("email")>
Public Property Email() As String
<JsonPropertyName("address")>
Public Property Address() As Address
End Class
所有使用者 ID 和姓名都會顯示在輸出中。
整個程式碼可在 Git 上獲取在此鏈接.
RestSharp 支援發送 XML 或 JSON 主體請求。 RestRequest
實例的 AddJsonBody 或 AddXmlBody 方法可用於添加 JSON 或 XML 主體。 RestSharp 會自動設置內容類型。
RestSharp 自動處理 JSON 或 XML 回應。
//using RestSharp;
// Serialize the user object to JSON
var jsonBodyString = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request data
var requestData = new RestRequest().AddJsonBody(jsonBodyString);
var response = client.ExecutePost(requestData);
//using RestSharp;
// Serialize the user object to JSON
var jsonBodyString = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request data
var requestData = new RestRequest().AddJsonBody(jsonBodyString);
var response = client.ExecutePost(requestData);
'using RestSharp;
' Serialize the user object to JSON
Dim jsonBodyString = JsonSerializer.Serialize(newUser)
' Create a RestRequest for the POST method with the JSON request data
Dim requestData = (New RestRequest()).AddJsonBody(jsonBodyString)
Dim response = client.ExecutePost(requestData)
RestSharp 也支持在請求主體中發送數據,這在創建或更新資源時很常見。 讓我們修改範例以展示 POST 請求 API:
using RestSharp;
var client = new RestClient("https://jsonplaceholder.typicode.com/users");
// New user object
var newUser = new User
{
Name = "John Doe",
Email = "john.doe@example.com"
};
// Serialize the user object to JSON
var jsonBody = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request body
var request = new RestRequest().AddJsonBody(jsonBody);
if (response.IsSuccessful)
{
// Output the response content
Console.WriteLine(response.Content);
}
else
{
Console.WriteLine($"Error: {response.ErrorMessage}");
}
using RestSharp;
var client = new RestClient("https://jsonplaceholder.typicode.com/users");
// New user object
var newUser = new User
{
Name = "John Doe",
Email = "john.doe@example.com"
};
// Serialize the user object to JSON
var jsonBody = JsonSerializer.Serialize(newUser);
// Create a RestRequest for the POST method with the JSON request body
var request = new RestRequest().AddJsonBody(jsonBody);
if (response.IsSuccessful)
{
// Output the response content
Console.WriteLine(response.Content);
}
else
{
Console.WriteLine($"Error: {response.ErrorMessage}");
}
Imports RestSharp
Private client = New RestClient("https://jsonplaceholder.typicode.com/users")
' New user object
Private newUser = New User With {
.Name = "John Doe",
.Email = "john.doe@example.com"
}
' Serialize the user object to JSON
Private jsonBody = JsonSerializer.Serialize(newUser)
' Create a RestRequest for the POST method with the JSON request body
Private request = (New RestRequest()).AddJsonBody(jsonBody)
If response.IsSuccessful Then
' Output the response content
Console.WriteLine(response.Content)
Else
Console.WriteLine($"Error: {response.ErrorMessage}")
End If
在此示例中,我們創建一個新的 User
對象,將其序列化為 JSON,並使用 AddJsonBody 方法將其包含在請求主體中。 服務器接收 JSON 資料並根據請求進行處理。
RestSharp 也支持發送帶有身份驗證的請求。 RestClientOptions 可以包含身份驗證參數。
var options = new RestClientOptions("https://auth.net"){Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret)};
var options = new RestClientOptions("https://auth.net"){Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret)};
Dim options = New RestClientOptions("https://auth.net") With {.Authenticator = New HttpBasicAuthenticator(_clientId, _clientSecret)}
在這裡,我們使用基本的客戶端 ID 密鑰驗證,並在每個請求中發送。
RestSharp 可以處理在 URL 請求期間發生的錯誤,例如超時、身份驗證或授權錯誤。 RestSharp 不會自動拋出請求失敗的異常。 需要手動配置。
可以進行以下錯誤處理配置:
ResponseStatus
設置為 Error
。var restClientOptions = new RestClientOptions(url) { ThrowOnAnyError = true };
var client = new RestClient(restClientOptions);
var restClientOptions = new RestClientOptions(url) { ThrowOnAnyError = true };
var client = new RestClient(restClientOptions);
Dim restClientOptions As New RestClientOptions(url) With {.ThrowOnAnyError = True}
Dim client = New RestClient(restClientOptions)
IronPDF是一個來自 的 C# PDF 庫Iron Software幫助讀取和生成 PDF 文檔。 它可以輕鬆地將包含樣式信息的格式化文件轉換成PDF。 IronPDF 能夠輕鬆從 HTML 內容生成 PDF; 它可以從 URL 下載 HTML,然後生成 PDF。
IronPDF 的一個關鍵特點是HTML 轉換為 PDF,保留所有佈局和樣式。 它將網頁內容轉換為PDF,非常適合報告、發票和文檔。 HTML 文件、URL 和 HTML 字串可以輕鬆轉換為 PDF。
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
若要將 IronPDF 整合到您的 Selenium RestSharp 專案中,請使用 NuGet 套件管理器並按照以下步驟進行:
打開 Visual Studio,然後在方案總管中右鍵點擊您的專案。
從上下文菜單中選擇「管理 NuGet 套件...」。
前往「瀏覽」標籤頁並搜尋 IronPDF。
從搜尋結果中選擇IronPDF程式庫,然後點擊安裝按鈕。
接受任何許可協議提示。
如果您想通過套件管理器控制台將 IronPDF 包含在您的專案中,請在套件管理器控制台中執行以下命令:
Install-Package IronPdf
這將會將 IronPDF 取回並安裝到您的專案中。
如需詳細了解 IronPDF,包括其功能、兼容性和其他下載選項,請訪問 NuGet 網站上的 IronPDF 頁面:https://www.nuget.org/packages/IronPdf。
或者,您可以使用其 DLL 文件直接將 IronPDF 整合到您的項目中。從中下載包含 DLL 的 ZIP 文件IronPDF 下載. 解壓縮並將 DLL 包含在您的專案中。
現在我們將獲取所有用戶,並使用 HTML 字串和 IronPDF 生成器生成 PDF 報告。
using System.Text.Json;
using System.Text.Json.Serialization;
using RestSharp;
namespace rest_sharp_demo;
class Program
{
static void Main()
{
// Create a RestClient
var baseUrl = "https://jsonplaceholder.typicode.com/users";
RestClientOptions options = new RestClientOptions(baseUrl) { UseDefaultCredentials = true };
var client = new RestClient(options);
// Create a RestRequest for the GET method
var request = new RestRequest();
// Execute the request and get the response
var response = client.Get(request);
// Check if the request was successful
if (response.IsSuccessful)
{
// Deserialize JSON response into a list of User objects
var users = JsonSerializer.Deserialize<List<User>>(response.Content);
// Generate Pdf
var html = GetHtml(users);
var Renderer = new ChromePdfRenderer();
var PDF = Renderer.RenderHtmlAsPdf(html);
PDF.SaveAs("UsersReport.pdf");
}
else
{
// Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
private static string GetHtml(List<User>? users)
{
string header = $@"
<html>
<head><title>Users List</title></head>
<body>
";
var footer = @"
</body>
</html>";
var htmlContent = header;
foreach (var user in users)
{
htmlContent += $@"
<h1>{user.Name}</h1>
<p>Username: {user.Username}</p>
<p>Email: {user.Email}</p>
<p>Company: {user.Company}</p>
<p>Phone: {user.Phone}</p>
<p>Website: {user.Website}</p>
<p>Suite: {user.Address.Suite}</p>
<p>Street: {user.Address.Street}</p>
<p>City: {user.Address.City}</p>
<p>Zipcode: {user.Address.Zipcode}</p>
";
}
htmlContent += footer;
return htmlContent;
}
}
using System.Text.Json;
using System.Text.Json.Serialization;
using RestSharp;
namespace rest_sharp_demo;
class Program
{
static void Main()
{
// Create a RestClient
var baseUrl = "https://jsonplaceholder.typicode.com/users";
RestClientOptions options = new RestClientOptions(baseUrl) { UseDefaultCredentials = true };
var client = new RestClient(options);
// Create a RestRequest for the GET method
var request = new RestRequest();
// Execute the request and get the response
var response = client.Get(request);
// Check if the request was successful
if (response.IsSuccessful)
{
// Deserialize JSON response into a list of User objects
var users = JsonSerializer.Deserialize<List<User>>(response.Content);
// Generate Pdf
var html = GetHtml(users);
var Renderer = new ChromePdfRenderer();
var PDF = Renderer.RenderHtmlAsPdf(html);
PDF.SaveAs("UsersReport.pdf");
}
else
{
// Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}");
}
}
private static string GetHtml(List<User>? users)
{
string header = $@"
<html>
<head><title>Users List</title></head>
<body>
";
var footer = @"
</body>
</html>";
var htmlContent = header;
foreach (var user in users)
{
htmlContent += $@"
<h1>{user.Name}</h1>
<p>Username: {user.Username}</p>
<p>Email: {user.Email}</p>
<p>Company: {user.Company}</p>
<p>Phone: {user.Phone}</p>
<p>Website: {user.Website}</p>
<p>Suite: {user.Address.Suite}</p>
<p>Street: {user.Address.Street}</p>
<p>City: {user.Address.City}</p>
<p>Zipcode: {user.Address.Zipcode}</p>
";
}
htmlContent += footer;
return htmlContent;
}
}
Imports System.Text.Json
Imports System.Text.Json.Serialization
Imports RestSharp
Namespace rest_sharp_demo
Friend Class Program
Shared Sub Main()
' Create a RestClient
Dim baseUrl = "https://jsonplaceholder.typicode.com/users"
Dim options As New RestClientOptions(baseUrl) With {.UseDefaultCredentials = True}
Dim client = New RestClient(options)
' Create a RestRequest for the GET method
Dim request = New RestRequest()
' Execute the request and get the response
Dim response = client.Get(request)
' Check if the request was successful
If response.IsSuccessful Then
' Deserialize JSON response into a list of User objects
Dim users = JsonSerializer.Deserialize(Of List(Of User))(response.Content)
' Generate Pdf
Dim html = GetHtml(users)
Dim Renderer = New ChromePdfRenderer()
Dim PDF = Renderer.RenderHtmlAsPdf(html)
PDF.SaveAs("UsersReport.pdf")
Else
' Handle the error
Console.WriteLine($"Error: {response.ErrorMessage}")
End If
End Sub
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: private static string GetHtml(List<User>? users)
Private Shared Function GetHtml(ByVal users As List(Of User)) As String
Dim header As String = $"
<html>
<head><title>Users List</title></head>
<body>
"
ignore ignore ignore ignore var footer = "
</body>
</html>"
ignore ignore var htmlContent = header
For Each user In users
htmlContent += $"
<h1>{user.Name}</h1>
<p>Username: {user.Username}</p>
<p>Email: {user.Email}</p>
<p>Company: {user.Company}</p>
<p>Phone: {user.Phone}</p>
<p>Website: {user.Website}</p>
<p>Suite: {user.Address.Suite}</p>
<p>Street: {user.Address.Street}</p>
<p>City: {user.Address.City}</p>
<p>Zipcode: {user.Address.Zipcode}</p>
"
ignore ignore ignore ignore ignore ignore ignore ignore ignore ignore ignore
Next user
htmlContent += footer
Return htmlContent
End Function
End Class
End Namespace
整個程式碼可以在 Git 中找到在此鏈接.
在此,我們首先從用戶列表中生成一個包含報告所需所有格式的 HTML 字串。 然後我們使用IronPDF生成PDF文件。 我們使用 "RenderHtmlAsPdf" 方法將 HTML 字串轉換為 PDF 文件。 生成的文件如下:
文件具有小的試用版浮水印,可以使用有效的授權來移除。
要讓上述代碼運行,需要許可證密鑰。 此密鑰需要放置在 appsettings.json
中。
"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
A試用授權開發人員註冊後即可使用,且試用許可證無需信用卡。 您可以提供您的電子郵件ID並註冊免費試用。
RestSharp 庫簡化了在 C# 中使用 RESTful API 的過程,提供了一種清晰且高效的方法來發送 HTTP 請求和處理回應。 無論您是使用 GET 請求來檢索數據,還是使用 POST 請求來發送數據,RestSharp 的直觀 API 及便利功能都為開發人員提供了寶貴的工具,以構建能與網絡服務互動的應用程式。
IronPDF提供一個靈活且易於使用的解決方案來生成PDF。 如需有關各種 IronPDF 功能的更多資訊,請造訪IronPDF 文件頁面.
IronPDF 的永久性授權將幫助您提高程式編寫技能並滿足現代應用程式需求。
了解RestSharp和IronPDF可以增加很好的技能,使開發人員能夠創建現代應用程式。