01
03/2016
c#程序模拟POST和GET请求
原文:http://stackoverflow.com/questions/4015324/http-request-with-post
有几种方式模拟GET和POST请求:
方法1:已过时
using System.Net; using System.Text; // for class Encoding
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();方法2:WebClient(现在也已经过时)
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");
}方法3:HttpClient
当前最好的方式,支持异步访问。
using System.Net.Http;
POST
using (var client = new HttpClient())
{
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
using (var client = new HttpClient())
{
var responseString = client.GetStringAsync("http://www.example.com/recepticle.aspx");
}方法4:第三方库
测试版本,支持REST API。便携式。可以通过NuGet获得。
更新的API,比较稳定,可以用于测试。底层是HttpClient。便携式,可以通过NuGet获得。
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();
转载请注明:康瑞部落 » c#程序模拟POST和GET请求

0 条评论