本文主要介绍.Net(C#)中,使用WebClient在程序后台(客户端/控制台程序)执行Get和Post请求,或者上传下载数据的方法及示例代码。WebClient主要面向了WEB网页场景,在模拟Web操作时使用较为方便。

1、执行Get请求下载数据

using System.Net;
using System.Collections.Specialized;
//发送Get请求
 string url = string.Format("http://localhost:28450/api/values?p1=a&p2=b");
 using (var wc = new WebClient())
{
 Encoding enc = Encoding.GetEncoding("UTF-8");
 Byte[] pageData = wc.DownloadData(url);
 string re = enc.GetString(pageData);
}
//执行Get请求
using (WebClient webClient = new WebClient())
using(Stream stream = webClient.OpenRead("http://example.com/data")    )
// 使用 StreamReader 读取 stream
using(StreamReader reader= new StreamReader(stream))
{
    // 將 StreamReader 所读取数据转成 string
    string request = reader.ReadToEnd();
    request.Dump();
}
// DownloadString(string)
using(WebClient webClient = new WebClient())
{
    // 指定 WebClient 的编码
    webClient.Encoding = Encoding.UTF8;
    // 指定 WebClient 的 Content-Type header
    webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    // 从url 上取得数据
    var body = webClient.DownloadString("http://example.com/data");
    body.Dump();
}

2、执行Post请求上传数据

using System.Net;
using System.Collections.Specialized;
//发送Post请求
//UploadValues (byte[])
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);
}
//UploadString(string)
using (WebClient webClient = new WebClient())
{
    // 指定 WebClient 编码
    webClient.Encoding = Encoding.UTF8;
    // 指定 WebClient 的 Content-Type header
    webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    // 指定 WebClient 的 authorization header
    webClient.Headers.Add("authorization", "token {apitoken}");
    // 准备写入的 data
    PostData postData = new PostData() { userId = 52013, title = "abc", body = "cjavapy" };
    // 将 data 转为 json
    string json = JsonConvert.SerializeObject(postData);
    // 执行 post请求
    var result = webClient.UploadString("http://www.example.com/recepticle.aspx", json);
    // linqpad 将 post 结果输出
    result.Dump();
}
// UploadData(byte[])
using (WebClient webClient = new WebClient())
{
    // 指定 WebClient 编码
    webClient.Encoding = Encoding.UTF8;
    // 指定 WebClient 的 Content-Type header
    webClient.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
    // 指定 WebClient 的 authorization header
    webClient.Headers.Add("authorization", "token {apitoken}");
    //要传的数据
    string postData = "id=12354&name=abc&body=cjavapy";
    //将要传的字串转为 byte array
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    // 执行post请求
    var result = webClient.UploadData("http://www.example.com/recepticle.aspx", byteArray);
    // linqpad 将 post结果输出
    result.Dump();
}

3、执行PUT请求

方法与 POST 相同,只需在 url 与 data 间多传一个 method 的参数。

// 建立 WebClient
using (WebClient webClient = new WebClient())
{
    // 指定 WebClient 编码
    webClient.Encoding = Encoding.UTF8;
    // 指定 WebClient 的 Content-Type header
    webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    // 指定 WebClient 的 authorization header
    webClient.Headers.Add("authorization", "token {apitoken}");
    // 执行 PUT 动作
    var result = webClient.UploadString("http://www.example.com/recepticle.aspx","PUT","");
    // linqpad 将 post 结果输出
    result.Dump();
}

4、执行DELETE请求

方法与 POST 相同,只需在 url 与 data 间多传一个 method 的参数。

// 建立 WebClient
using (WebClient webClient = new WebClient())
{
    // 指定 WebClient 编码
    webClient.Encoding = Encoding.UTF8;
    // 指定 WebClient 的 Content-Type header
    webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    // 指定 WebClient 的 authorization header
    webClient.Headers.Add("authorization", "token {apitoken}");
    // 执行 DELETE 动作
    var result = webClient.UploadString("http://www.example.com/recepticle.aspx",    "DELETE", "");
    // linqpad 将 post 结果输出
    result.Dump();
}

5、执行PATCH请求

方法与 POST 相同,只需在 url 与 data 间多传一个 method 的参数。

// 建立 WebClient
using (WebClient webClient = new WebClient())
{
    // 指定 WebClient 编码
    webClient.Encoding = Encoding.UTF8;
    // 指定 WebClient 的 Content-Type header
    webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    // 指定 WebClient 的 authorization header
    webClient.Headers.Add("authorization", "token {api token}");
    // 准备写入的 data
    PostData postData = new PostData() { title = "abc", body = "cjavapy"     };
    // 将 data 转为 json
    string json = JsonConvert.SerializeObject(postData);
    // 执行 PATCH 动作
    var result = webClient.UploadString("http://www.example.com/recepticle.aspx","PATCH", json);
    // linqpad 将 post 结果输出
    result.Dump();
}

6、使用proxy(代理服务器)

// 建立 WebClient
using (WebClient webClient = new WebClient())
{
    // 指定 WebClient 编码
    webClient.Encoding = Encoding.UTF8;
    // 指定 WebClient 的 Content-Type header
    webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    // 指定 WebClient 的 authorization header
    webClient.Headers.Add("authorization", "token {api token}");
    //指令 proxy address
    string proxyAddress = "http://127.0.0.1:8080";
    //建立 proxy
    WebProxy myProxy = new WebProxy(new Uri(proxyAddress));
    //建立 proxy 的认证信息
    myProxy.Credentials = new NetworkCredential("{username}", "{password}");
    //将 proxy 指定给 request 使用
    webClient.Proxy = myProxy;
    // 准备写入的 data
    PostData postData = new PostData() { userId=5201314, title = "abc", body = "cjavapy" };
    // 将 data 转为 json
    string json = JsonConvert.SerializeObject(postData);
    // 执行 post 动作
    var result = webClient.UploadString("http://www.example.com/recepticle.aspx", json);
    // linqpad 将 post 结果输出
    result.Dump();
}

相关文档.Net(C#)后台发送Get和Post请求的几种方法总结

推荐文档