首页 / C#开发 / 正文

[C#].NET/C#应用程序开发中如何使用WebClient向指定的远程请求地址发送(POST)数据?

3273 发布于: 2018-05-10 读完约需6分钟

问题描述

在.NET/C#应用程序开发过程中,需要使用WebClient类向指定的远程请求地址发送(HTTP POST)数据。

当然,我们可不使用WebClient这个类而是使用WebRequest来发送HTTP请求,但如果由于特定的原因,一定要使用WebClient来处理,应该怎么实现,有哪些方式呢?

方案一

使用WebClient,然后设置请求头部的ContentTypeapplication/x-www-form-urlencoded,再调用WebClient实例的UploadString()方法,如下:

string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";

using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(URI, myParameters);
}

方案二

WebClient内置了许多方法,其中有一个UploadValue()的方法,可以发送HTTP POST(或者其他任意的HTTP请求的方式)请求,在这个方法中,我们可以传入NameValueCollection的键值集合,如下:

using(WebClient client = new WebClient())
{
    var reqparm = new System.Collections.Specialized.NameValueCollection();
    reqparm.Add("param1", "<any> kinds & of = ? strings");
    reqparm.Add("param2", "escaping is already handled");
    byte[] responsebytes = client.UploadValues("http://localhost", "POST", reqparm);
    string responsebody = Encoding.UTF8.GetString(responsebytes);
}

方案三

使用WebClientUploadData()方法,我们可以轻松地向远程服务请求地址POST数据,以下是一个以WebClient.UploadData()为示例的实现,如下:

byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
                System.Text.Encoding.ASCII.GetBytes("field1=value1&amp;field2=value2") );

            string sret = System.Text.Encoding.ASCII.GetString(bret);

方案四

string URI = "site.com/mail.php";
using (WebClient client = new WebClient())
{
    System.Collections.Specialized.NameValueCollection postData = 
        new System.Collections.Specialized.NameValueCollection()
       {
              { "to", emailTo },  
              { "subject", currentSubject },
              { "body", currentBody }
       };
    string pagesource = Encoding.UTF8.GetString(client.UploadValues(URI, postData));
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [Visual Studio]使用命令行制作Visual Studio 2017的离线安装包并离线安装Visual Studio 2017

下一篇: [ASP.NET MVC]在ASP.NET MVC WEB网站应用程序开发中如何处理全局错误(403错误,404错误等等)?

本文永久链接码友网 » [C#].NET/C#应用程序开发中如何使用WebClient向指定的远程请求地址发送(POST)数据?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册