天天看點

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);
           

繼續閱讀