在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
休息站是一个流行的开源 .NET 库,用于用 C# 发出 HTTP 请求。 它简化了使用 RESTful API 的过程,提供了一种直接而灵活的网络服务通信方式。 在本文中,我们将探讨以下工具的关键功能休息站和IronPDF并演示如何提取数据和生成 PDF。
在现代多层应用程序中,不同的服务需要经常相互通信,而 RestSharp 通过封装所有复杂的功能提供了一种简单高效的方法。 这将大大简化软件开发过程。
RestSharp 可作为NuGet您可以在您的 C# 项目中安装该工具包。 您可以使用 NuGet 软件包管理器控制台或Visual StudioNuGet 软件包管理器用户界面
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 还使用 async 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 不会抛出异常。 需要手动配置。
可以进行以下错误处理配置:
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是一个来自铁软件该工具有助于阅读和生成 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
要使用 NuGet 包管理器将 IronPDF 集成到 Selenium RestSharp 项目中,请按照以下步骤操作:
打开 Visual Studio,在 "解决方案资源管理器 "中右键单击您的项目。
从上下文菜单中选择 "管理 NuGet 软件包..."。
转到 "浏览 "选项卡,搜索 IronPDF。
从搜索结果中选择 IronPdf 库,然后点击安装按钮。
接受任何许可协议提示。
如果您想通过软件包管理器控制台在项目中包含 IronPdf,那么请在软件包管理器控制台中执行以下命令:
Install-Package IronPdf
它会获取 IronPDF 并将其安装到你的项目中。
有关 IronPDF 的详细概述,包括其功能、兼容性和其他下载选项,请访问 NuGet 网站上的 IronPDF 页面 https://www.nuget.org/packages/IronPdf。
另外,您也可以使用 IronPdf 的 DLL 文件将其直接集成到您的项目中。从以下地址下载包含 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试用许可开发人员只需注册即可使用《.NET.COM》,试用许可证无需信用卡。 您可以提供自己的电子邮件 ID 并注册免费试用。
RestSharp 库简化了在 C# 中使用 RESTful API 的过程,提供了一种简洁高效的方式来发出 HTTP 请求并处理响应。 无论是使用 GET 请求检索数据还是使用 POST 请求发送数据,RestSharp 直观的 API 和便捷的功能都使其成为开发人员构建与网络服务交互的应用程序的重要工具。
IronPDFPDFGroup 提供了灵活易用的 PDF 生成解决方案。 有关 IronPDF 各种功能的更多信息,请访问IronPDF 文档页面.
IronPDF 的永续性许可证我们的翻译将帮助您提高编码技能,满足现代应用程序的要求。
同时了解 RestSharp 和 IronPdf 可以增加很好的技能,使开发人员能够创建现代应用程序。