HttpClient 使用請求數據
0、初始化及全局設置
//初始化:必須先執行一次
#!import ./ini.ipynb
1、使用url 傳參
參數放在Url里,形如:http://www.baidu.com?name=zhangsan&age=18, GET、Head請求用的比較多。優點是簡單、方便,能被瀏覽器緩存;缺點是參數長度等限制較多,數據暴露url中,可能比較長。
/**URL傳參:適合簡單數據類型
*/
{//獲取響應字符串{var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=1");response.EnsureSuccessStatusCode();var content = await response.Content.ReadAsStringAsync();Console.WriteLine(content);}//獲取響應對象{var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=1");response.EnsureSuccessStatusCode();var result = await response.Content.ReadFromJsonAsync<BaseResult<Account>>();result.Display();}//直接獲取響應對象{var result = await SharedClient.GetFromJsonAsync<BaseResult<Account>>("api/Normal/GetAccount?id=1");result.Display();}}
2、使用路由傳參
路由參數,指參數使為URL的一部分,一般由后端API設定好,前端按規定使用即可。例如:后端指定/user/:id,前端使用/user/1,此時id為路由參數。
/*
** 路由參數:參數是URL的一部分,由后端指定
*/
{//大括號:方便折疊、開成單獨的作用域var response = await SharedClient.GetAsync("api/Normal/GetAccount/管理員01");//確定是成功的響應response.EnsureSuccessStatusCode();//獲取響應內容var content = await response.Content.ReadAsStringAsync();//輸出 Console.WriteLine(content);
}
3、使用請求頭
把請求數據放入請求頭中,傳給后端。當然也可以傳多個數據。不過,請求頭中傳數據限制比較多,一般只傳簡單的數據:比如jwt token 。
/*
* 請求頭: 值必須是字符串,如果有中文等需進行編碼
*/
{//設置請求頭//中文先編碼,服務端接收后要解碼var codedName = System.Net.WebUtility.UrlEncode("管理員01");//SharedClient是共用的,所以不能多次添加,先移除舊值if (SharedClient.DefaultRequestHeaders.Contains("name")){SharedClient.DefaultRequestHeaders.Remove("name");}//添加請求頭SharedClient.DefaultRequestHeaders.Add("name", codedName);var response = await SharedClient.GetAsync("api/Normal/GetAccountFromHeader");//確定是成功的響應response.EnsureSuccessStatusCode();//獲取響應內容var content = await response.Content.ReadAsStringAsync();//輸出 Console.WriteLine(content);
}
4、使用請求體
把數據放在請求體中,發送到服務端。可以是簡單的字符串,也可以是二進制數據(上傳文件)、form表單項、編碼過的form表單項、json、流式數據等形式,甚至是這個類型的組合。
說下個人的幾點理解:
1、不管哪種請求體數據,都是放在請求體中,以二進制形式通過網絡發往服務器,由服務器接收使用。客戶端發送請求數據需要與服務端接收相配合;
2、客戶端通過Content-Typey請求頭設置,告訴服務端請求發送的是哪種類型的數據;服務端根據Content-Type來識別、解析請求數據。常見的類型有:multipart/form-data、application/x-www-form-urlencoded、application/json、text/plain等;
3、ASP.NET Core中,默認的請求體類型是FormUrlEncodedContent,所以默認情況下,客戶端發送的請求數據是form表單項; asp.net 框架對json格式數據和表單數據進行了特殊處理,支持參數綁定等,可以使用[FromBody]特性,將請求數據綁定到對應的模型上。但普通的文本類型等不支持綁定等功能,需要從請求體中獲取原始數據,自行處理。
4、一次可發送多種格式數據,由統一的分隔符分隔。服務端可以從請求頭[] Content-Type: multipart/mixed; boundary=“d2e38916-df08-4fec-a40e-3e5179736f32”]拿到分隔符,然后根據分隔符將數據拆分出來。
HttpClient 中,請求體也分為這幾種(常見的)類型:
- MultipartFormDataContent
- FormUrlEncodedContent
- JsonContent
- StringContent
- ByteArrayContent
- StreamContent
- MultipartContent
MultipartFormDataContent :Form表單
Form表單,提交數據方式之一。
/*
* Form表單,提交數據。一般為Put或Post提交。
*/
{// 創建一個 MultipartFormDataContent 對象, 用來存入 Form表單 各項及值var formContent = new MultipartFormDataContent();// 添加表單字段formContent.Add(new StringContent("1"), "id");formContent.Add(new StringContent("管理員01"), "name");// 發送POST請求var response = await SharedClient.PostAsync("api/AdvancedGet/PostFormData", formContent);// 讀取響應內容string responseString = await response.Content.ReadAsStringAsync();Console.WriteLine(responseString);
}
FormUrlEncodedContent :Form表單 asp.net core 默認接收方式
/*FormUrlEncoded 提交數據
*/
{//設置數據項var urlEncodedData = new List<KeyValuePair<string,string>>(){new KeyValuePair<string,string>(key:"id",value:"1"),new KeyValuePair<string,string>(key:"name",value:"管理員01"),};//FormUrlEncodedContent對象var formContent = new FormUrlEncodedContent(urlEncodedData);// 發送POST請求var response = await SharedClient.PostAsync("api/AdvancedGet/PostFormData", formContent);// 讀取響應內容string responseString = await response.Content.ReadAsStringAsync();Console.WriteLine(responseString);
}
StringContent 普通文本(也包括很多格式,甚至是自定義格式。要和服務器配合)
/*普通文本方式提交數據
*/
{var requestContent = new StringContent("我是請求體第一段內容", Encoding.UTF8, "text/plain");var response = await SharedClient.PostAsync("/api/AdvancedPost/TextData", requestContent);var content = await response.Content.ReadAsStringAsync();Console.WriteLine(content);
}