C# HttpClient (Geliştiriciler İçin Nasıl Çalışır)
HttpClient sınıfı, .NET Framework'ün bir parçasıdır ve bir URI tarafından tanımlanan bir kaynaktan HTTP istekleri göndermek ve HTTP yanıtları almak için yöntemler sağlar. HTTP istek çağrısını yapmak, ister GET, POST, PUT, ister DELETE isteklerini gerçekleştirin, basitleştirir. Bu kılavuz, pratik senaryolarda HttpClient'in temel kullanımını kapsayacak ve IronPDF kütüphanesini tanıtacak.
Yeni bir HttpClient Örneği Oluşturma
HttpClient sınıfı HTTP istekleri göndermek için kullanılır. Aşağıdaki gibi yeni bir örneğini oluşturabilirsiniz:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using var client = new HttpClient(); // Create a new instance of HttpClient
// Send a GET request to the specified URI and store the HTTP response
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London");
// Retrieve the response content as a string
var responseBody = await response.Content.ReadAsStringAsync();
// Print the response content to the console
Console.WriteLine(responseBody);
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using var client = new HttpClient(); // Create a new instance of HttpClient
// Send a GET request to the specified URI and store the HTTP response
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London");
// Retrieve the response content as a string
var responseBody = await response.Content.ReadAsStringAsync();
// Print the response content to the console
Console.WriteLine(responseBody);
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient() ' Create a new instance of HttpClient
' Send a GET request to the specified URI and store the HTTP response
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London")
' Retrieve the response content as a string
Dim responseBody = Await response.Content.ReadAsStringAsync()
' Print the response content to the console
Console.WriteLine(responseBody)
End Function
End Class
Bu örnekte:
- Yeni bir HttpClient örneği
var client = new HttpClient()kullanılarak oluşturulur. - Bir HTTP GET isteği
GetAsyncyöntemi kullanılarak gönderilir. HttpResponseMessage,var responseiçinde saklanır.- Yanıtın içeriği
response.Content.ReadAsStringAsync()kullanılarak alınır.
HTTP İsteği Gönderme
HTTP GET İsteği
Bir HTTP GET isteği yapmak ve cevabı işlemek için:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris");
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris");
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Paris")
' Check if the request was successful
If response.IsSuccessStatusCode Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
End If
End Function
End Class
IsSuccessStatusCodeözelliği, isteğin başarılı olduğunu garanti eder.- Yanıt gövdesi
ReadAsStringAsync()ile eşzamansız olarak okunur.
HTTP POST İsteği
Bir POST isteği göndermek, bir istek gövdesi eklemeyi içerir:
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"New York\" }", Encoding.UTF8, "application/json");
// Send the POST request with the specified body
var response = await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"New York\" }", Encoding.UTF8, "application/json");
// Send the POST request with the specified body
var response = await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
Imports System
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
Dim requestBody = New StringContent("{ ""location"": ""New York"" }", Encoding.UTF8, "application/json")
' Send the POST request with the specified body
Dim response = Await client.PostAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody)
' Check if the request was successful
If response.IsSuccessStatusCode Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
End If
End Function
End Class
PostAsync, belirlenen gövde ile (requestBody) isteği gönderir.- İçerik türü belirtilmelidir (application/json).
HTTP PUT İsteği
Bir HTTP PUT isteği kaynakları günceller:
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"Tokyo\", \"days\": 3 }", Encoding.UTF8, "application/json");
// Send a PUT request to update the resource
var response = await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var requestBody = new StringContent("{ \"location\": \"Tokyo\", \"days\": 3 }", Encoding.UTF8, "application/json");
// Send a PUT request to update the resource
var response = await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody);
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
Imports System
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
Dim requestBody = New StringContent("{ ""location"": ""Tokyo"", ""days"": 3 }", Encoding.UTF8, "application/json")
' Send a PUT request to update the resource
Dim response = Await client.PutAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY", requestBody)
' Check if the request was successful
If response.IsSuccessStatusCode Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
End If
End Function
End Class
PutAsync, belirlenen URI'daki kaynağı güncellemek için bir PUT isteği gönderir.- İstek gövdesi genellikle güncellenecek verileri içerir.
HTTP DELETE İsteği
HTTP DELETE isteği göndermek için:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
// Send a DELETE request to remove the resource
var response = await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY");
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Resource deleted successfully");
}
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
// Send a DELETE request to remove the resource
var response = await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY");
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Resource deleted successfully");
}
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
' Send a DELETE request to remove the resource
Dim response = Await client.DeleteAsync("https://api.weatherapi.com/v1/locations/1?key=YOUR_API_KEY")
' Check if the request was successful
If response.IsSuccessStatusCode Then
Console.WriteLine("Resource deleted successfully")
End If
End Function
End Class
DeleteAsync, kaynağı kaldırmak için bir DELETE isteği gönderir.
HTTP Yanıtlarını İşleme
Her HTTP isteği bir HttpResponseMessage nesnesi döndürür, bu nesne yanıt içeriği, başlıklar ve durum kodu içerir. Örneğin:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney");
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
}
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney");
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
}
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Sydney")
' Check if the request was successful
If response.IsSuccessStatusCode Then
Dim responseBody = Await response.Content.ReadAsStringAsync()
Console.WriteLine(responseBody)
Else
Console.WriteLine($"Error: {response.StatusCode}")
End If
End Function
End Class
Response.StatusCode, durum kodunu (ör. 200, 404) sağlar.response.Content, yanıt gövdesini içerir veReadAsStringAsync()kullanılarak eşzamansız olarak okunabilir.
HttpClient'nin Verimli Kullanımı
HttpClient örnekleri, bağlantı havuzlamasını kullanmak ve sistem kaynaklarını tüketmekten kaçınmak için yeniden kullanılmalıdır. Tipik bir model, uygulamanızın veya hizmetinizin ömrü boyunca tek bir HttpClient örneği oluşturmaktır. Bu, statik bir değişken kullanılarak veya web uygulamaları için bağımlılık enjeksiyonu ile yapılabilir.
Statik HttpClient Örneği
public static class HttpClientProvider
{
private static readonly HttpClient client = new HttpClient();
public static HttpClient Client => client;
}
public static class HttpClientProvider
{
private static readonly HttpClient client = new HttpClient();
public static HttpClient Client => client;
}
Public Module HttpClientProvider
'INSTANT VB NOTE: The field client was renamed since Visual Basic does not allow fields to have the same name as other class members:
Private ReadOnly client_Conflict As New HttpClient()
Public ReadOnly Property Client() As HttpClient
Get
Return client_Conflict
End Get
End Property
End Module
HttpClient örneği uygulama genelinde yeniden kullanılarak yeni HTTP bağlantılarının oluşturulması için gerekli olan ek yükü azaltır.
HttpClient'i Bağımlılık Enjeksiyonu İle Kullanma
Bir web uygulamasında, HttpClient'i bir singleton hizmet olarak kaydetmek önerilen yaklaşımdır:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
services.AddHttpClient()
End Sub
Daha belirli konfigürasyonlar için adlandırılmış müşteriler ve tipik müşteriler de oluşturabilirsiniz.
Bağlantı Havuzlama ve Proxy Ayarları
HttpClient örneklerini yeniden kullanarak, aynı sunucuya yapılan çoklu isteklerin performansını iyileştiren bağlantı havuzlamasının avantajlarından yararlanırsınız. Ayrıca HttpClientHandler sınıfını kullanarak proxy ayarlarını yapılandırabilirsiniz:
using System.Net;
using System.Net.Http;
var handler = new HttpClientHandler
{
Proxy = new WebProxy("http://proxyserver:port"), // Set the proxy server
UseProxy = true
};
var client = new HttpClient(handler);
using System.Net;
using System.Net.Http;
var handler = new HttpClientHandler
{
Proxy = new WebProxy("http://proxyserver:port"), // Set the proxy server
UseProxy = true
};
var client = new HttpClient(handler);
Imports System.Net
Imports System.Net.Http
Private handler = New HttpClientHandler With {
.Proxy = New WebProxy("http://proxyserver:port"),
.UseProxy = True
}
Private client = New HttpClient(handler)
Hata Yapısı ve Durum Kodları
Farklı HTTP durum kodlarını işlemek için HttpResponseMessage.StatusCode özelliğini kontrol edin:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
async Task MakeRequestAsync()
{
try
{
using var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Berlin");
// Handle the response based on the status code
switch (response.StatusCode)
{
case HttpStatusCode.OK:
Console.WriteLine("Success");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Response content: {content}");
break;
case HttpStatusCode.NotFound:
Console.WriteLine("Resource not found");
break;
case HttpStatusCode.Unauthorized:
Console.WriteLine("Unauthorized access");
break;
case HttpStatusCode.InternalServerError:
Console.WriteLine("Server error occurred");
break;
default:
Console.WriteLine($"Unexpected status code: {response.StatusCode}");
break;
}
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
catch (Exception e)
{
Console.WriteLine($"An error occurred: {e.Message}");
}
}
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
async Task MakeRequestAsync()
{
try
{
using var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Berlin");
// Handle the response based on the status code
switch (response.StatusCode)
{
case HttpStatusCode.OK:
Console.WriteLine("Success");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Response content: {content}");
break;
case HttpStatusCode.NotFound:
Console.WriteLine("Resource not found");
break;
case HttpStatusCode.Unauthorized:
Console.WriteLine("Unauthorized access");
break;
case HttpStatusCode.InternalServerError:
Console.WriteLine("Server error occurred");
break;
default:
Console.WriteLine($"Unexpected status code: {response.StatusCode}");
break;
}
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
catch (Exception e)
{
Console.WriteLine($"An error occurred: {e.Message}");
}
}
Imports System
Imports System.Net
Imports System.Net.Http
Imports System.Threading.Tasks
Async Function MakeRequestAsync() As Task
Try
Dim client = New HttpClient()
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Berlin")
' Handle the response based on the status code
Select Case response.StatusCode
Case HttpStatusCode.OK
Console.WriteLine("Success")
Dim content = Await response.Content.ReadAsStringAsync()
Console.WriteLine($"Response content: {content}")
Case HttpStatusCode.NotFound
Console.WriteLine("Resource not found")
Case HttpStatusCode.Unauthorized
Console.WriteLine("Unauthorized access")
Case HttpStatusCode.InternalServerError
Console.WriteLine("Server error occurred")
Case Else
Console.WriteLine($"Unexpected status code: {response.StatusCode}")
End Select
Catch e As HttpRequestException
Console.WriteLine($"Request error: {e.Message}")
Catch e As Exception
Console.WriteLine($"An error occurred: {e.Message}")
End Try
End Function
JSON Yanıt İçeriği İşleme
Genellikle JSON yanıtları ile çalışırsınız. Yanıt içeriğini güçlü tipli bir nesneye dönüştürebilirsiniz:
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London");
var jsonString = await response.Content.ReadAsStringAsync();
// Deserialize the JSON response into a WeatherResponse object
var weatherResponse = JsonSerializer.Deserialize<WeatherResponse>(jsonString);
Console.WriteLine($"Location: {weatherResponse.Location}, Temperature: {weatherResponse.Temperature}");
}
}
public class WeatherResponse
{
public string Location { get; set; }
public double Temperature { get; set; }
}
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
class Example
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London");
var jsonString = await response.Content.ReadAsStringAsync();
// Deserialize the JSON response into a WeatherResponse object
var weatherResponse = JsonSerializer.Deserialize<WeatherResponse>(jsonString);
Console.WriteLine($"Location: {weatherResponse.Location}, Temperature: {weatherResponse.Temperature}");
}
}
public class WeatherResponse
{
public string Location { get; set; }
public double Temperature { get; set; }
}
Imports System
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks
Friend Class Example
Shared Async Function Main(ByVal args() As String) As Task
Dim client = New HttpClient()
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London")
Dim jsonString = Await response.Content.ReadAsStringAsync()
' Deserialize the JSON response into a WeatherResponse object
Dim weatherResponse = JsonSerializer.Deserialize(Of WeatherResponse)(jsonString)
Console.WriteLine($"Location: {weatherResponse.Location}, Temperature: {weatherResponse.Temperature}")
End Function
End Class
Public Class WeatherResponse
Public Property Location() As String
Public Property Temperature() As Double
End Class
JSON içeriğini doğrudan C# nesnelerine okumayı basitleştiren yöntem ReadAsStringAsync().
IronPDF'i Tanıtma

IronPDF, C# ile PDF belgeleri oluşturmak, yönetmek ve dönüştürmek için tasarlanmış bir .NET PDF kütüphanesidir. HTML, CSS, JavaScript ve diğer formatlardan yüksek kaliteli PDF'ler oluşturmak için yaygın olarak kullanılır. IronPDF, HTML'den PDF'ye dönüştürme, PDF birleştirme, filigran ekleme ve hatta dijital imza gibi ileri düzey işlemleri, PDF şifrelemeyi ve daha fazlasını sunan özellikler sunar. Windows, Linux ve macOS dahil olmak üzere çeşitli platformlarla uyumlu olup, çapraz platform geliştirme için çok yönlüdür.
IronPDF ile HttpClient Kullanmak
IronPDF'i C#'ta HttpClient sınıfı ile birleştirmek, web kaynaklarından dinamik olarak PDF belgeleri oluşturmak ve yönetmek için etkili bir yoldur. Örneğin, HttpClient kullanarak bir URL'den HTML içeriği alabilir ve bu HTML'yi IronPDF kullanarak bir PDF belgesine dönüştürebilirsiniz. Bu, canlı web içeriği temel alınmış raporlar, faturalar veya her türlü belge oluştururken kullanışlı olur.
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using IronPdf;
class Program
{
static async Task Main(string[] args)
{
License.LicenseKey = "YOUR_LICENSE_KEY"; // Set your IronPDF license key
using var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY&q=London&days=3");
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var jsonContent = await response.Content.ReadAsStringAsync();
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonContent);
// Format the JSON content for pretty-printing
var formattedJson = JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });
// Escape the JSON for HTML
formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson);
// Create an HTML string for PDF generation
var htmlContent = $@"
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; }}
pre {{ background-color: #f4f4f4; padding: 20px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
</style>
</head>
<body>
<h1>Weather Forecast (JSON Data)</h1>
<pre>{formattedJson}</pre>
</body>
</html>";
// Generate the PDF from the HTML content
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF to a file
pdf.SaveAs("F://weather_report.pdf");
Console.WriteLine("PDF generated successfully!");
}
else
{
Console.WriteLine($"Failed to retrieve content. Status code: {response.StatusCode}");
}
}
}
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using IronPdf;
class Program
{
static async Task Main(string[] args)
{
License.LicenseKey = "YOUR_LICENSE_KEY"; // Set your IronPDF license key
using var client = new HttpClient();
var response = await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY&q=London&days=3");
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
var jsonContent = await response.Content.ReadAsStringAsync();
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonContent);
// Format the JSON content for pretty-printing
var formattedJson = JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });
// Escape the JSON for HTML
formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson);
// Create an HTML string for PDF generation
var htmlContent = $@"
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; }}
pre {{ background-color: #f4f4f4; padding: 20px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
</style>
</head>
<body>
<h1>Weather Forecast (JSON Data)</h1>
<pre>{formattedJson}</pre>
</body>
</html>";
// Generate the PDF from the HTML content
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF to a file
pdf.SaveAs("F://weather_report.pdf");
Console.WriteLine("PDF generated successfully!");
}
else
{
Console.WriteLine($"Failed to retrieve content. Status code: {response.StatusCode}");
}
}
}
Imports System
Imports System.Net.Http
Imports System.Text.Json
Imports System.Threading.Tasks
Imports IronPdf
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
License.LicenseKey = "YOUR_LICENSE_KEY" ' Set your IronPDF license key
Dim client = New HttpClient()
Dim response = Await client.GetAsync("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY&q=London&days=3")
' Check if the request was successful
If response.IsSuccessStatusCode Then
Dim jsonContent = Await response.Content.ReadAsStringAsync()
Dim jsonElement = JsonSerializer.Deserialize(Of JsonElement)(jsonContent)
' Format the JSON content for pretty-printing
Dim formattedJson = JsonSerializer.Serialize(jsonElement, New JsonSerializerOptions With {.WriteIndented = True})
' Escape the JSON for HTML
formattedJson = System.Web.HttpUtility.HtmlEncode(formattedJson)
' Create an HTML string for PDF generation
Dim htmlContent = $"
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; }}
pre {{ background-color: #f4f4f4; padding: 20px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
</style>
</head>
<body>
<h1>Weather Forecast (JSON Data)</h1>
<pre>{formattedJson}</pre>
</body>
</html>"
' Generate the PDF from the HTML content
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF to a file
pdf.SaveAs("F://weather_report.pdf")
Console.WriteLine("PDF generated successfully!")
Else
Console.WriteLine($"Failed to retrieve content. Status code: {response.StatusCode}")
End If
End Function
End Class

Gerçek bir hava durumu API'si kullanırken, "YOUR_API_KEY" ifadesini bir API anahtarı ile değiştirmeyi unutmayın.
Sonuç

Bu ders, C#'ta HttpClient sınıfını kullanarak HTTP istekleri göndermeyi ve yanıtları işlemeyi ele aldı. Ayrıca, .NET uygulamalarında PDF oluşturmak için güçlü bir kütüphane olan IronPDF'i tanıttık. Bu teknolojileri birleştirmeyi, bir web hizmetinden HttpClient aracılığıyla HTML içeriği alarak ve IronPDF kullanarak bunu PDF'ye dönüştürerek gösterdik.
IronPDF, ücretsiz bir deneme sunar ve lisansları $799 dan başlar, bu da onu kapsamlı PDF oluşturma kapasiteleri arayan geliştiriciler için değerli bir araç haline getirir.
Sıkça Sorulan Sorular
HTML içeriğini C#'de nasıl PDF'ye dönüştürebilirim?
HTML içeriğini PDF'e dönüştürmek için IronPDF'i kullanabilir, RenderHtmlAsPdf gibi yöntemlerini kullanabilirsiniz. Bu, CSS ve JavaScript ile birlikte HTML dizgilerini kolayca profesyonel PDF belgelerine dönüştürmenize olanak tanır.
C#'de HttpClient'i PDF oluşturma işlemiyle nasıl birleştiririm?
HttpClient'i IronPDF ile entegre ederek web kaynaklarından HTML içeriği alabilir ve ardından bu içeriği IronPDF'in dönüşüm yöntemlerini kullanarak PDF belgelerine dönüştürebilirsiniz. Bu, gerçek zamanlı verilerden raporlar veya faturalar oluşturmak için özellikle kullanışlıdır.
HttpClient örneklerini yeniden kullanmanın önemi nedir?
HttpClient örneklerini yeniden kullanmak, verimli kaynak yönetimi için çok önemlidir. Bağlantı havuzlamasını kullanarak her istek için yeni bağlantı oluşturmanın getirdiği yükü en aza indirir, bu da uygulamaların performansını artırır.
C#'de JSON yanıtlarını nasıl deserialize ederim?
C#'de, JSON yanıtları JsonSerializer sınıfı kullanılarak deserialize edilebilir. Yanıt içeriğini bir dizge olarak aldıktan sonra, JsonSerializer.Deserialize kullanarak güçlü bir şekilde tiplendirilmiş C# nesnesine dönüştürebilirsiniz.
C#'de HTTP durum kodlarını yönetmenin en iyi pratikleri nelerdir?
C#'de HTTP durum kodlarını yönetme, HttpResponseMessage'ın StatusCode özelliğini kontrol etmeyi içerir. Belirli kodları, HttpStatusCode.OK veya HttpStatusCode.NotFound gibi, yönetmek için koşullu ifadeler kullanın ve uygun hata yönetimini uygulayın.
IronPDF, PDF yetenekleri ile .NET uygulamalarını nasıl geliştirir?
IronPDF, PDF dosyalarını oluşturma, işleme ve dönüştürme için sağlam araçlar sağlayarak .NET uygulamalarını geliştirir. HTML, CSS ve JavaScript'ten yüksek kaliteli PDF oluşturmayı destekler, geliştiricilere dinamik belgeler üretiminde kolaylık sunar.
HttpClient'i PDF dönüşümü için HTML içeriği almakta kullanabilir miyim?
Evet, HttpClient, web kaynaklarından HTML içeriği alabilir, bu da ardından IronPDF kullanılarak PDF'e dönüştürülebilir. Bu yöntem, canlı web verilerinden veya dinamik içerikten PDF oluşturma için mükemmeldir.
C#'de HttpClient için proxy ayarlarını nasıl yapılandırırım?
HttpClient için proxy ayarlarını yapılandırmak için HttpClientHandler sınıfını kullanabilirsiniz. Bir WebProxy örneğine Proxy özelliğini ayarlayın ve HttpClient örneği oluştururken UseProxy seçeneğini etkinleştirin.




