1. 程式人生 > 其它 >c# 模擬Http請求

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來安裝

新增引用

using System.Net.Http;

例項化

建議在你應用程式的生命週期中使用同一個 HttpClient的例項

private static readonly HttpClient client = new HttpClient();

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

GET傳送請求

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

二、使用RestSharp

可以通過Nuget:https://www.nuget.org/packages/RestSharp來安裝,具體使用示例:

傳送請求

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

Nuget安裝

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

using Flurl.Http;

POST傳送請求

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

GET傳送請求

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

四、使用HttpWebRequest

引入名稱空間

適用的.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

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

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

引入名稱空間

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

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

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

GET傳送請求

using (var client = new WebClient())
{
    var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}