You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
HttpClientStudy/Docs/1.3.2.基础使用.使用请求数据.ipynb

493 lines
15 KiB
Plaintext

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"dotnet_interactive": {
"language": "csharp"
},
"polyglot_notebook": {
"kernelName": "csharp"
}
},
"source": [
"# HttpClient 使用请求数据"
]
},
{
"cell_type": "markdown",
"metadata": {
"dotnet_interactive": {
"language": "csharp"
},
"polyglot_notebook": {
"kernelName": "csharp"
},
"vscode": {
"languageId": "polyglot-notebook"
}
},
"source": [
"## 0、初始化及全局设置"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"dotnet_interactive": {
"language": "csharp"
},
"polyglot_notebook": {
"kernelName": "csharp"
},
"vscode": {
"languageId": "polyglot-notebook"
}
},
"outputs": [
{
"data": {
"text/html": [
"<div><div></div><div></div><div><strong>Installed Packages</strong><ul><li><span>Microsoft.Extensions.Http, 8.0.0</span></li><li><span>Microsoft.Net.Http.Headers, 8.0.8</span></li><li><span>System.Net.Http.Json, 8.0.0</span></li></ul></div></div>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"配置文件根目录e:\\王高峰\\我的项目\\学习项目\\HttpClientStudy\\Docs\\Publish\\HttpClientStudy.Core\n",
"启动WebApi项目\n",
"程序[e:\\王高峰\\我的项目\\学习项目\\HttpClientStudy\\Docs\\Publish\\HttpClientStudy.WebApp\\HttpClientStudy.WebApp.exe]已在新的命令行窗口执行。如果未出现新命令行窗口,可能是程序错误造成窗口闪现!\n"
]
}
],
"source": [
"//初始化,只执行一次\n",
"\n",
"// 引用nuget包和类库文件\n",
"#r \"nuget:System.Net.Http.Json\"\n",
"#r \"nuget:Microsoft.Net.Http.Headers\"\n",
"#r \"nuget:Microsoft.Extensions.Http\"\n",
"#r \"./Publish/HttpClientStudy.Model/HttpClientStudy.Model.dll\"\n",
"#r \"./Publish/HttpClientStudy.Core/HttpClientStudy.Core.dll\"\n",
"\n",
"//全局引用\n",
"global using System;\n",
"global using System.Collections;\n",
"global using System.Linq;\n",
"global using System.Linq.Expressions;\n",
"global using System.Threading;\n",
"global using System.Threading.Tasks;\n",
"global using System.Net.Http;\n",
"global using System.Net.Mime;\n",
"global using System.Net.Http.Json;\n",
"\n",
"global using HttpClientStudy.Config;\n",
"global using HttpClientStudy.Model;\n",
"global using HttpClientStudy.Core;\n",
"global using HttpClientStudy.Core.Utilities;\n",
"\n",
"//全局变量\n",
"var webApiBaseUrl = WebApiConfigManager.GetWebApiConfig().BaseUrl;\n",
"var workDir = Environment.CurrentDirectory;\n",
"var fullPath = System.IO.Path.GetFullPath(\"./Publish/HttpClientStudy.WebApp/HttpClientStudy.WebApp.exe\", workDir);\n",
"\n",
"//全局共享静态 HttpClient 对象\n",
"public static HttpClient SharedClient = new HttpClient(new SocketsHttpHandler(){ PooledConnectionIdleTimeout = TimeSpan.FromSeconds(30)})\n",
"{\n",
" BaseAddress = new Uri(WebApiConfigManager.GetWebApiConfig().BaseUrl),\n",
"};\n",
"\n",
"//启动已发布的WebApi项目\n",
"{\n",
" Console.WriteLine(\"启动WebApi项目\");\n",
" var startMessage = AppUtility.RunWebApiExeFile(fullPath);\n",
" Console.WriteLine(startMessage);\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1、使用url 传参"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"参数放在Url里形如http://www.baidu.com?name=zhangsan&age=18, GET、Head请求用的比较多。优点是简单、方便能被浏览器缓存缺点是参数长度等限制较多数据暴露url中可能比较长。"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"vscode": {
"languageId": "polyglot-notebook"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\"data\":{\"id\":1,\"name\":\"管理员01\",\"password\":\"123456\",\"role\":\"Admin\"},\"code\":1,\"message\":\"成功\"}\r\n"
]
},
{
"data": {
"text/html": [
"<details open=\"open\" class=\"dni-treeview\"><summary><span class=\"dni-code-hint\"><code>HttpClientStudy.Model.BaseResult`1[HttpClientStudy.Model.Account]</code></span></summary><div><table><thead><tr></tr></thead><tbody><tr><td>Data</td><td><div class=\"dni-plaintext\"><pre>HttpClientStudy.Model.BaseResult`1[HttpClientStudy.Model.Account]</pre></div></td></tr><tr><td>Code</td><td><div class=\"dni-plaintext\"><pre>1</pre></div></td></tr><tr><td>Message</td><td><div class=\"dni-plaintext\"><pre>成功</pre></div></td></tr><tr><td>Data</td><td><div class=\"dni-plaintext\"><pre>HttpClientStudy.Model.BaseResult`1[HttpClientStudy.Model.Account]</pre></div></td></tr></tbody></table></div></details><style>\r\n",
".dni-code-hint {\r\n",
" font-style: italic;\r\n",
" overflow: hidden;\r\n",
" white-space: nowrap;\r\n",
"}\r\n",
".dni-treeview {\r\n",
" white-space: nowrap;\r\n",
"}\r\n",
".dni-treeview td {\r\n",
" vertical-align: top;\r\n",
" text-align: start;\r\n",
"}\r\n",
"details.dni-treeview {\r\n",
" padding-left: 1em;\r\n",
"}\r\n",
"table td {\r\n",
" text-align: start;\r\n",
"}\r\n",
"table tr { \r\n",
" vertical-align: top; \r\n",
" margin: 0em 0px;\r\n",
"}\r\n",
"table tr td pre \r\n",
"{ \r\n",
" vertical-align: top !important; \r\n",
" margin: 0em 0px !important;\r\n",
"} \r\n",
"table th {\r\n",
" text-align: start;\r\n",
"}\r\n",
"</style>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<details open=\"open\" class=\"dni-treeview\"><summary><span class=\"dni-code-hint\"><code>HttpClientStudy.Model.BaseResult`1[HttpClientStudy.Model.Account]</code></span></summary><div><table><thead><tr></tr></thead><tbody><tr><td>Data</td><td><div class=\"dni-plaintext\"><pre>HttpClientStudy.Model.BaseResult`1[HttpClientStudy.Model.Account]</pre></div></td></tr><tr><td>Code</td><td><div class=\"dni-plaintext\"><pre>1</pre></div></td></tr><tr><td>Message</td><td><div class=\"dni-plaintext\"><pre>成功</pre></div></td></tr><tr><td>Data</td><td><div class=\"dni-plaintext\"><pre>HttpClientStudy.Model.BaseResult`1[HttpClientStudy.Model.Account]</pre></div></td></tr></tbody></table></div></details><style>\r\n",
".dni-code-hint {\r\n",
" font-style: italic;\r\n",
" overflow: hidden;\r\n",
" white-space: nowrap;\r\n",
"}\r\n",
".dni-treeview {\r\n",
" white-space: nowrap;\r\n",
"}\r\n",
".dni-treeview td {\r\n",
" vertical-align: top;\r\n",
" text-align: start;\r\n",
"}\r\n",
"details.dni-treeview {\r\n",
" padding-left: 1em;\r\n",
"}\r\n",
"table td {\r\n",
" text-align: start;\r\n",
"}\r\n",
"table tr { \r\n",
" vertical-align: top; \r\n",
" margin: 0em 0px;\r\n",
"}\r\n",
"table tr td pre \r\n",
"{ \r\n",
" vertical-align: top !important; \r\n",
" margin: 0em 0px !important;\r\n",
"} \r\n",
"table th {\r\n",
" text-align: start;\r\n",
"}\r\n",
"</style>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"/**\n",
" URL传参适合简单数据类型\n",
"*/\n",
"{\n",
" //获取响应字符串\n",
" {\n",
" var response = await SharedClient.GetAsync(\"api/Normal/GetAccount?id=1\");\n",
" response.EnsureSuccessStatusCode();\n",
" var content = await response.Content.ReadAsStringAsync();\n",
" Console.WriteLine(content);\n",
" }\n",
"\n",
" //获取响应对象\n",
" {\n",
" var response = await SharedClient.GetAsync(\"api/Normal/GetAccount?id=1\");\n",
" response.EnsureSuccessStatusCode();\n",
"\n",
" var result = await response.Content.ReadFromJsonAsync<BaseResult<Account>>();\n",
" result.Display();\n",
" }\n",
"\n",
" //直接获取响应对象\n",
" {\n",
" var result = await SharedClient.GetFromJsonAsync<BaseResult<Account>>(\"api/Normal/GetAccount?id=1\");\n",
" result.Display();\n",
" }\n",
" \n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2、使用路由传参"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"路由参数指参数使为URL的一部分一般由后端API设定好前端按规定使用即可。例如后端指定/user/:id前端使用/user/1此时id为路由参数。"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"vscode": {
"languageId": "polyglot-notebook"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\"data\":{\"id\":1,\"name\":\"管理员01\",\"password\":\"123456\",\"role\":\"Admin\"},\"code\":1,\"message\":\"成功\"}\r\n"
]
}
],
"source": [
"/*\n",
"** 路由参数参数是URL的一部分,由后端指定\n",
"*/\n",
"{//大括号:方便折叠、开成单独的作用域\n",
"\n",
" var response = await SharedClient.GetAsync(\"api/Normal/GetAccount/管理员01\");\n",
" \n",
" //确定是成功的响应\n",
" response.EnsureSuccessStatusCode();\n",
"\n",
" //获取响应内容\n",
" var content = await response.Content.ReadAsStringAsync();\n",
"\n",
" //输出 \n",
" Console.WriteLine(content);\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3、使用请求头"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"把请求数据放入请求头中传给后端。当然也可以传多个数据。不过请求头中传数据限制比较多一般只传简单的数据比如jwt token 。"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"vscode": {
"languageId": "polyglot-notebook"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\"data\":{\"id\":1,\"name\":\"管理员01\",\"password\":\"123456\",\"role\":\"Admin\"},\"code\":1,\"message\":\"成功\"}\r\n"
]
}
],
"source": [
"/*\n",
"* 请求头: 值必须是字符串,如果有中文等需进行编码\n",
"*/\n",
"{\n",
" //设置请求头\n",
"\n",
" //中文先编码,服务端接收后要解码\n",
" var codedName = System.Net.WebUtility.UrlEncode(\"管理员01\");\n",
"\n",
" //SharedClient是共用的所以不能多次添加,先移除旧值\n",
" if (SharedClient.DefaultRequestHeaders.Contains(\"name\"))\n",
" {\n",
" SharedClient.DefaultRequestHeaders.Remove(\"name\");\n",
" }\n",
" \n",
" //添加请求头\n",
" SharedClient.DefaultRequestHeaders.Add(\"name\", codedName);\n",
"\n",
" var response = await SharedClient.GetAsync(\"api/Normal/GetAccountFromHeader\");\n",
" \n",
" //确定是成功的响应\n",
" response.EnsureSuccessStatusCode();\n",
"\n",
" //获取响应内容\n",
" var content = await response.Content.ReadAsStringAsync();\n",
"\n",
" //输出 \n",
" Console.WriteLine(content);\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4、使用Form表单"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"简单的Form表单提交数据。其实是把数据放请求值的一种后页有详细介绍。"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"vscode": {
"languageId": "polyglot-notebook"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\"data\":\"Id=1&name=管理员01\",\"code\":1,\"message\":\"成功\"}\r\n"
]
}
],
"source": [
"/*\n",
"* Form表单提交数据。一般为Put或Post提交。\n",
"*/\n",
"{\n",
" // 创建一个MultipartFormDataContent对象,用来存入 Form表单独项及值\n",
" var formContent = new MultipartFormDataContent();\n",
" \n",
" // 添加表单字段\n",
" formContent.Add(new StringContent(\"1\"), \"id\");\n",
" formContent.Add(new StringContent(\"管理员01\"), \"name\");\n",
" \n",
" // 发送POST请求\n",
" var response = await SharedClient.PostAsync(\"api/AdvancedGet/PostFormData\", formContent);\n",
" \n",
" // 读取响应内容\n",
" string responseString = await response.Content.ReadAsStringAsync();\n",
" \n",
" Console.WriteLine(responseString);\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5、使用请求体"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"把数据放在请求体中,发送到服务端。可以是简单的字符串,也可以是二进制数据(上传文件)、form表单项、编码过的form表单项、json、流式数据等形式甚至是这个类型的组合。\n",
"所以请求体也分为这几种(常见的)类型:\n",
"1. StringContent\n",
"2. ByteArrayContent\n",
"3. FormUrlEncodedContent\n",
"4. JsonContent\n",
"5. StreamContent\n",
"6. MultipartContent\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"vscode": {
"languageId": "polyglot-notebook"
}
},
"source": [
"### StringContent 普通文本(也包括很多格式,甚至是自定义格式。要和服务器配合)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "polyglot-notebook"
}
},
"outputs": [],
"source": [
"{\n",
" StringContent content = new StringContent(\"\",Encoding.UTF8, System.Net.Mime.MediaTypeNames.Text.Plain);\n",
"}"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".NET (C#)",
"language": "C#",
"name": ".net-csharp"
},
"language_info": {
"name": "python"
},
"polyglot_notebook": {
"kernelInfo": {
"defaultKernelName": "csharp",
"items": [
{
"aliases": [],
"name": "csharp"
}
]
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}