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