.jpg)
如何发出 HTTP POST 请求并在正文中发送数据?
网友回答:
简单的 GET 请求
using System.Net;
...
using (var wb = new WebClient())
{
var response = wb.DownloadString(url);
}
简单的开机自检请求
using System.Net;
using System.Collections.Specialized;
...
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["username"] = "myUser";
data["password"] = "myPassword";
var response = wb.UploadValues(url, "POST", data);
string responseInString = Encoding.UTF8.GetString(response);
}
网友回答:
有几种方法可以执行 HTTP GET 和 POST 请求:
在以下版本中可用:.NET Framework 4.5+、.NET Standard 1.1+ 和 .NET Core 1.0+。
它是当前首选的方法,并且是异步和高性能的。在大多数情况下使用内置版本,但对于非常旧的平台,有一个 NuGet 包。
using System.Net.Http;
建议在应用程序的生存期内实例化一个并共享它,除非你有特定原因不这样做。HttpClient
private static readonly HttpClient client = new HttpClient();
有关依赖项注入解决方案,请参阅。HttpClientFactory
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();
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
休息夏普
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}");
request.AddParameter("thing1", "Hello");
request.AddParameter("thing2", "world");
request.AddHeader("header", "value");
request.AddFile("file", path);
var response = client.Post(request);
var content = response.Content; // Raw content as string
var response2 = client.Post<Person>(request);
var name = response2.Data.Name;
Flurl.Http
它是一个较新的库,具有流畅的API,测试助手,在引擎盖下使用HttpClient,并且是可移植的。它可通过 NuGet 获得。
using Flurl.Http;
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();
在以下版本中可用:.NET Framework 1.1+、.NET Standard 2.0+、.NET Core 1.0+。在 .NET Core 中,它主要是为了兼容性 – 它包装 ,性能较低,并且不会获得新功能。HttpClient
using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("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();
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
这是一个包装器。儗。HttpWebRequestHttpClient
在以下版本中可用:.NET Framework 1.1+、NET Standard 2.0+ 和 .NET Core 2.0+。
在某些情况下(.NET Framework 4.5-4.8),如果需要同步执行 HTTP 请求,仍然可以使用。WebClient
using System.Net;
using System.Collections.Specialized;
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())
{
var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}
网友回答:
MSDN 有一个示例。
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestPostExample
{
public static void Main()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
模板简介:该模板名称为【如何发出 HTTP POST 请求并在正文中发送数据?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【C#】栏目查找您需要的精美模板。