隐藏

.NET/C#发起GET和POST请求的几种方法

发布:2019/12/26 17:48:31作者:管理员 来源:本站 浏览次数:1046

.NET/C#发起GET和POST请求的几种方法

第一种:HttpWebRequest

using System.Net; 

GET:

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

POST:

quest = (HttpWebRequest)WebRequest.Create("http://www.leadnt.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(); 

第二种:WebClient,也过时了:

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

GET:

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

POST:

using (var client = new WebClient())
{
    var values = new NameValueCollection();
    values["thing1"] = "hello";
    values["thing2"] = "world";
 
    var response = client.UploadValues("http://www.leadnt.com/recepticle.aspx", values);
 
    var responseString = Encoding.Default.GetString(response);
} 

第三种:HttpClient 当前主流用法,异步请求,自.NET4.5开始可从Nuget包管理中获取。

using System.Net.Http; 
  • 1

GET:

using (var client = new HttpClient())
{
    var responseString = client.GetStringAsync("http://www.mydomain.com/recepticle.aspx");
} 

POST:

using (var client = new HttpClient())
{
    var values = new List<KeyValuePair<string, string>>();
    values.Add(new KeyValuePair<string, string>("thing1", "hello"));
    values.Add(new KeyValuePair<string, string>("thing2 ", "world"));
 
    var content = new FormUrlEncodedContent(values);
 
    var response = await client.PostAsync("http://www.mydomain.com/recepticle.aspx", content);
 
    var responseString = await response.Content.ReadAsStringAsync();
} 

第四种:第三方类库:

RestSharp

REST API请求测试类库,可通过 NuGet 获得。

Flurl.Http

最新的便捷的api测试工具,使用HttpClient实现,可通过 NuGet 安装。

using Flurl.Http; 
  • 1

GET:

var responseString = await "http://www.mydomain.com/recepticle.aspx"
    .GetStringAsync(); 
  • 1
  • 2

POST:

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

原文地址https://www.cnblogs.com/xdot/p/6306508.html