.NET[C#]中如何模拟发送HTTP请求(GET,POST,PUT,DELETE等)

.NET 作者: Rector 1409阅读 0评论 0收藏 收藏本文

郑重申明:本文未经许可,禁止任何形式转载

.NET[C#]中如何模拟发送HTTP请求(GET,POST,PUT,DELETE等)

方式一、使用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:

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

阅读了该文章的人还浏览了...

本文永久链接码友网 » .NET[C#]中如何模拟发送HTTP请求(GET,POST,PUT,DELETE等)

发布于: 2017-12-30 08:25:00
分享扩散:

文章评论

获取验证码