c# 模拟Http请求

一、使用HttpClient

适用的.NET Framework 版本包括:.NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+
你可以通过Nuget:https://www.nuget.org/packages/Microsoft.Net.Http来安装

1.1 添加引用

using System.Net.Http;

1.2 实例化

建议在你应用程序的生命周期中使用同一个 HttpClient的实例

private static readonly HttpClient client = new HttpClient();

1.3 POST发送请求

var values = new Dictionary<string, string>
{
   { "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.4 GET发送请求

var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");

二、使用RestSharp

可以通过Nuget:https://www.nuget.org/packages/RestSharp来安装,具体使用示例:

2.1 发送请求

var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);

var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource

// easily add HTTP Headers
request.AddHeader("header", "value");

// add files to upload (works with compatible verbs)
request.AddFile(path);

// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string

// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;

// easy async support
client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Content);
});

// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
    Console.WriteLine(response.Data.Name);
});

// abort the request on demand
asyncHandle.Abort();

三、使用Flurl.Http

3.1 Nuget安装

Nuget地址:https://www.nuget.org/packages/Flurl.Http

using Flurl.Http;

3.2 POST发送请求

var responseString = await "http://www.example.com/recepticle.aspx"
    .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
    .ReceiveString();

3.3 GET发送请求

var responseString = await "http://www.example.com/recepticle.aspx"
    .GetStringAsync();

四、使用HttpWebRequest

4.1 引入命名空间

适用的.NET framework: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+

using System.Net;
using System.Text;  // for class Encoding
using System.IO;    // for StreamReader

4.2 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();

4.3 GET发送请求

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

五、使用WebClient

5.1 引入命名空间

适用的.NET framework: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+

using System.Net;
using System.Collections.Specialized;

5.2 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);
}

//或者
using (var client = new WebClient())
{
    byte[] dataToPost = Encoding.Default.GetBytes("thing1=hello&thing2=world");
    client.Header.Add("Content-Type","application/x-www-form-urlencoded");  //采用Post必须要加的Header,如果改成GET的话可以除去
    byte[] response = client.UploadData("http://example.com","POST",dataToPost);
    string strResult = Encoding.UTF8.GetString(response);
}

5.3 GET发送请求

using (var client = new WebClient())
{
    var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}
posted @ 2021-08-06 15:13  Ysの陈憨憨  阅读(844)  评论(0编辑  收藏  举报