在 C# 中使用 WebClient.DownloadString 发送 POST

发布于 2024-12-18 02:31:06 字数 248 浏览 0 评论 0原文

我知道关于使用 C# 发送 HTTP POST 请求存在很多问题,但我正在寻找一种使用 WebClient 而不是 HttpWebRequest 的方法。这可能吗?那就太好了,因为 WebClient 类非常易于使用。

我知道我可以设置 Headers 属性来设置某些标头,但我不知道是否可以实际从 WebClient 执行 POST。

I know there are a lot of questions about sending HTTP POST requests with C#, but I'm looking for a method that uses WebClient rather than HttpWebRequest. Is this possible? It'd be nice because the WebClient class is so easy to use.

I know I can set the Headers property to have certain headers set, but I don't know if it's possible to actually do a POST from WebClient.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终遇你 2024-12-25 02:31:06

您可以使用使用 HTTP POST 的 WebClient.UploadData(),即:

using (WebClient wc = new WebClient())
{
    byte[] result = wc.UploadData("http://stackoverflow.com", new byte[] { });
}

您指定的有效负载数据将作为请求的 POST 正文传输。

或者,可以使用 WebClient.UploadValues() 上传名称-值收集也通过 HTTP POST。

You can use WebClient.UploadData() which uses HTTP POST, i.e.:

using (WebClient wc = new WebClient())
{
    byte[] result = wc.UploadData("http://stackoverflow.com", new byte[] { });
}

The payload data that you specify will be transmitted as the POST body of your request.

Alternatively there is WebClient.UploadValues() to upload a name-value collection also via HTTP POST.

彩扇题诗 2024-12-25 02:31:06

您可以将 Upload 方法与 HTTP 1.0 POST 一起使用

string postData = Console.ReadLine();

using (System.Net.WebClient wc = new System.Net.WebClient())
{
    wc.Headers.Add("Content-Type","application/x-www-form-urlencoded");
    // Upload the input string using the HTTP 1.0 POST method.
    byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData);
    byte[] byteResult= wc.UploadData("http://targetwebiste","POST",byteArray);
    // Decode and display the result.
    Console.WriteLine("\nResult received was {0}",
                      Encoding.ASCII.GetString(byteResult));
}

You could use Upload method with HTTP 1.0 POST

string postData = Console.ReadLine();

using (System.Net.WebClient wc = new System.Net.WebClient())
{
    wc.Headers.Add("Content-Type","application/x-www-form-urlencoded");
    // Upload the input string using the HTTP 1.0 POST method.
    byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData);
    byte[] byteResult= wc.UploadData("http://targetwebiste","POST",byteArray);
    // Decode and display the result.
    Console.WriteLine("\nResult received was {0}",
                      Encoding.ASCII.GetString(byteResult));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文