C# WebClient几种常用方法的用法

1、UploadData方法(Content-Type:application/x-www-form-urlencoded)

//创建WebClient 对象
WebClient webClient = new WebClient();
//地址
string path = "http://******";
//需要上传的数据
string postString = "username=***&password=***&grant_type=***";
//以form表单的形式上传
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// 转化成二进制数组
byte[] postData = Encoding.UTF8.GetBytes(postString);
// 上传数据
byte[] responseData = webClient.UploadData(path, "POST", postData);
//获取返回的二进制数据
string result = Encoding.UTF8.GetString(responseData);

2、UploadData方法(Content-Type:application/json)

//创建WebClient 对象
WebClient webClient = new WebClient();
//地址
string path = "http://******";
//需要上传的数据
string jsonStr = "{"pageNo":1,"pageSize":3,"keyWord":""}";

//如果调用的方法需要身份验证则必须加如下请求标头
string token = "eyJhbGciOiJSUzI…";
webClient.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {token}");

//或者webClient.Headers.Add("Authorization", $"Bearer {token}");

//以json的形式上传
webClient.Headers.Add("Content-Type", "application/json");
// 转化成二进制数组
byte[] postData = Encoding.UTF8.GetBytes(jsonStr);
// 上传数据
byte[] responseData = webClient.UploadData(path, "POST", postData);
//获取返回的二进制数据
string result = Encoding.UTF8.GetString(responseData);

3、DownloadData方法

WebClient webClient = new WebClient();
string path = "http://******";

//如果调用的方法需要身份验证则必须加如下请求标头
string token = "eyJhbGciOiJSUzI1NiIs…";
webClient.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {token}");

// 下载数据
byte[] responseData = webClient.DownloadData(path);
string result = Encoding.UTF8.GetString(responseData);

4、DownloadString方法

//创建WebClient 对象
WebClient webClient = new WebClient();
//地址
string path = "http://******";

//如果调用的方法需要身份验证则必须加如下请求标头
string token = "eyJhbGciOiJSUzI1NiIsI…";
//设置请求头–名称/值对
webClient.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {token}");
//设置请求查询条件–名称/值对
webClient.QueryString.Add("type_S", "我的类型");
// 下载数据
string responseData = webClient.DownloadString(path);

 

你可能感兴趣的:(C#,winform,post,WebClient)