首页 > 后端开发 > C++ > 如何在.NET中使用正文数据发送HTTP POST请求?

如何在.NET中使用正文数据发送HTTP POST请求?

Patricia Arquette
发布: 2025-02-02 16:26:09
原创
245 人浏览过

.NET 中发送包含正文数据的 HTTP POST 请求方法详解

本文介绍在 .NET 中发送 HTTP POST 请求并传递正文数据的几种方法。

How to Send HTTP POST Requests with Body Data in .NET?

1. HttpClient (推荐)

对于 .NET Core 和更新版本的 .NET Framework,HttpClient 是首选的 HTTP 请求方法。它提供异步和高性能操作。

using System.Net.Http;
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);
登录后复制

2. 第三方库

RestSharp:

using RestSharp;
var client = new RestClient("http://example.com");
var request = new RestRequest("resource/{id}");
request.AddParameter("thing1", "Hello");
request.AddParameter("thing2", "world");
var response = client.Post(request);
登录后复制

Flurl.Http:

using Flurl.Http;
var responseString = await "http://www.example.com/recepticle.aspx"
    .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
    .ReceiveString();
登录后复制

3. HttpWebRequest (不推荐用于新项目)

POST:

using System.Net;
using System.Text;
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);
using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); }
var response = request.GetResponse();
登录后复制

GET:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = request.GetResponse();
登录后复制

4. WebClient (不推荐用于新项目)

POST:

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);
}
登录后复制

GET:

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

本文比较了多种.NET发送HTTP POST请求的方法,并建议使用HttpClient。 对于新项目,强烈建议使用HttpClient,因为它更现代化,性能更高,并且支持异步操作。

以上是如何在.NET中使用正文数据发送HTTP POST请求?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板