简介:
.NET (C#) 中,发送 HTTP GET 和 POST 请求可以通过多种方式实现,主要依赖于 .NET Framework 或 .NET Core/5+ 的版本。.NET中提供了多种方法来发送HTTP请求,每种方法都有其优缺点。选择哪种方法取决于具体需求和环境。
1、HttpClient 类 (推荐)
HttpClient 是 .NET 中处理 HTTP 请求的现代方法。它是线程安全的,支持异步操作,并且可以用于多个请求。
适用平台:.NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+
其它平台的移植版本可以通过Nuget来安装。(Nuget使用方法:http://www.cjavapy.com/article/21/)
命名空间:using System.Net.Http;
HttpClient推荐使用单一实例共享使用,发关请求的方法推荐使用异步的方式,代码如下,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace ConsoleApplication
{
class Program
{
private static readonly HttpClient client = new HttpClient();
static void Main(string[] args)
{
//发送Get请求
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
//发送Post请求
var values = new Dictionary
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
2、使用第三方类库
除了上述方法,还有许多第三方库可以用于发送HTTP请求,例如 RestSharp 和 Flurl。这些库通常提供更高级的功能,例如支持多种身份验证方法和自动重试机制。
1)Flurl.Http(可以通过Nuget来安装)
Flurl.Http 是一个在 .NET 环境下使用的流行的 HTTP 客户端库。它提供了一个简洁的 API 来创建 HTTP 请求,并支持异步操作。Flurl.Http 使得发送 HTTP 请求、接收响应、处理异常和解析数据变得非常简单。
命名空间:using Flurl.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Flurl.Http;
namespace ConsoleApplication
{
class Program
{
public static async Task Main(string[] args)
{
// 示例URL
string getUrl = "https://example.com";
string postUrl = "https://example.com/post";
// 发送GET请求
string htmlContent = await GetHtmlAsync(getUrl);
Console.WriteLine("GET请求结果:");
Console.WriteLine(htmlContent);
// 发送POST请求
var postData = new { Name = "John", Age = 30 };
var postResponse = await PostJsonAsync<object>(postUrl, postData);
Console.WriteLine("POST请求结果:");
Console.WriteLine(postResponse);
// 发送带有查询参数和头信息的GET请求
string htmlContentWithHeaders = await GetHtmlWithHeadersAsync(getUrl);
Console.WriteLine("带查询参数和头信息的GET请求结果:");
Console.WriteLine(htmlContentWithHeaders);
// 安全地发送GET请求
string safeHtmlContent = await SafeRequestAsync(getUrl);
Console.WriteLine("安全GET请求结果:");
Console.WriteLine(safeHtmlContent);
}
public static async Task<string> GetHtmlAsync(string url)
{
return await url.GetStringAsync();
}
public static async Task<TResponse> PostJsonAsync<TResponse >(string url, object data)
{
return await url
.PostJsonAsync(data)
.ReceiveJson<TResponse>();
}
public static async Task<string> GetHtmlWithHeadersAsync(string url)
{
return await url
.SetQueryParams(new { param1 = "value1", param2 = "value2" })
.WithHeader("Accept", "application/json")
.GetStringAsync();
