简介:
.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();
}
public static async Task<string> SafeRequestAsync(string url)
{
try
{
return await url.GetStringAsync();
}
catch (FlurlHttpException ex)
{
return "HTTP Error: " + ex.Message;
}
catch (Exception ex)
{
return "General Error: " + ex.Message;
}
}
}
}
- 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
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
2)RestSharp(可以通过Nuget来安装)
RestSharp 是一个用于在 .NET 中发送 HTTP 请求的简单 REST 和 HTTP API 客户端。它可以用于构建和发送各种 HTTP 请求,并处理响应。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//发送Get和Post请求
RestClient client = new RestClient("http://example.com");//指定请求的url
RestRequest req = new RestRequest("resource/{id}", Method.GET);//指定请求的方式,如果Post则改成Method.POST
request.AddParameter("name", "value"); // 添加参数到 URL querystring
request.AddUrlSegment("id", "123"); //替换上面指定请求方式中的{id}参数
//req.AddBody(body); /*如发送post请求,则用req.AddBody ()指定body内容*/
//发送请求得到请求的内容
//如果有header可以使用下面方法添加
//request.AddHeader("header", "value");
IRestResponse response = client.Execute(request);
//上传一个文件
//request.AddFile("file", path);
var content = response.Content; // 未处理的content是string
//还可以下面几种方式发送请求
//发送请求,反序列化请求结果
IRestResponse response2 = client.Execute(request);
var name = response2.Data.Name;
//发送请求下载一个文件,并保存到path路径
client.DownloadData(request).SaveAs(path);
// 简单发送异步请求
await client.ExecuteAsync(request);
// 发送异常请求并且反序列化结果
var asyncHandle = client.ExecuteAsync(request, response => {
Console.WriteLine(response.Data.Name);
});
//终止异步的请求
asyncHandle.Abort();
}
}
}
- 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
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
3、WebRequest 和 WebResponse
较旧的方法,现在通常推荐使用 HttpClient
。但在一些旧项目或特定场景下,WebRequest
和 WebResponse
仍然有用。
适用平台:.NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO; // for StreamReader
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//发送Get请求
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
//发送Post请求
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=hello";
postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
}
- 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
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
4、通过WebClient的方式发送请求
C#中,WebClient类提供了一个简单的方法来发送和接收数据到和从一个URI(如一个网页或Web服务)上。
适用平台:.NET Framework 1.1+, .NET Standard 2.0+, .NET Core 2.0+
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Specialized;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//发送Get请求
string url = string.Format("http://localhost:28450/api/values?p1=a&p2=b");
using (var wc = new WebClient())
{
Encoding enc = Encoding.GetEncoding("UTF-8");
Byte[] pageData = wc.DownloadData(url);
string re = enc.GetString(pageData);
}
//发送Post请求
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);
var responseString = Encoding.Default.GetString(response);
}
}
}
}
- 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
- 29
- 30
- 31
- 32
- 33
- 34
- 35
了解更多分析及数据抓取可查看:
http://data.yisurvey.com:8989/
特别说明:本文旨在技术交流,请勿将涉及的技术用于非法用途,否则一切后果自负。如果您觉得我们侵犯了您的合法权益,请联系我们予以处理。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?