公交车上荫蒂添的好舒服的电影-公用玩物(np双xing总受)-公用小荡货芊芊-公与妇仑乱hd-攻把受做哭边走边肉楼梯play-古装一级淫片a免费播放口

LOGO OA教程 ERP教程 模切知識(shí)交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

C#使用HttpClient四種請(qǐng)求數(shù)據(jù)格式:json、表單數(shù)據(jù)、文件上傳、xml格式

admin
2024年6月8日 18:15 本文熱度 1767

前言

當(dāng)下編寫應(yīng)用程序都流行前后端分離,后端提供對(duì)應(yīng)服務(wù)接口給前端或跨應(yīng)用程序調(diào)用,如WebAPI等。在調(diào)用這些服務(wù)接口發(fā)送HTTP請(qǐng)求,而.NET為我們提供了HttpWebRequest、HttpClient幾個(gè)類庫來實(shí)現(xiàn)。下面對(duì)C#使用HttpClient類發(fā)送HTTP請(qǐng)求數(shù)據(jù)的幾種格式。

HttpClient

HttpClient是.NET 4.5以上版提供的類(System.Net.Http),編寫的應(yīng)用程序可以通過此類發(fā)送HTTP請(qǐng)求并從WEB服務(wù)公開的資源接收HTTP響應(yīng)。HTTP請(qǐng)求包含了請(qǐng)求報(bào)文與響應(yīng)報(bào)文。下面先簡(jiǎn)單的了解它的一些屬性與方法。
屬性:
屬性描述
BaseAddress獲取或設(shè)置發(fā)送請(qǐng)求時(shí)地址。
DefaultProxy獲取或設(shè)置全局HTTP請(qǐng)求代理。
DefaultRequestHeaders獲取請(qǐng)求發(fā)送的標(biāo)題。
DefaultRequestVersion獲取或設(shè)置請(qǐng)求使用的默認(rèn)HTTP版本。
MaxResponseContentBufferSize獲取或設(shè)置讀取響應(yīng)內(nèi)容時(shí)要緩沖的最大字節(jié)數(shù)。
Timeout獲取或設(shè)置請(qǐng)求超時(shí)等待的時(shí)間。
方法:
方法描述
GetAsync異步請(qǐng)求獲取指定URI。
GetByteArrayAsync異步請(qǐng)求獲取指定URI并以字節(jié)數(shù)組的形式返回響應(yīng)。
GetStreamAsync異步請(qǐng)求獲取指定URI并以流的形式返回響應(yīng)。
GetStringAsync異步請(qǐng)求獲取指定URI并以字符串的形式返回響應(yīng)正文。
PostAsync異步將POST請(qǐng)求發(fā)送給指定URI。
Send發(fā)送帶有指定請(qǐng)求的 HTTP 請(qǐng)求。
SendAsync以異步操作發(fā)送 HTTP 請(qǐng)求。

數(shù)據(jù)格式

在向HTTP發(fā)起請(qǐng)求時(shí),將以什么樣的數(shù)據(jù)格式發(fā)送數(shù)據(jù),這取決于URI服務(wù)資源。而常用的類型可分為application/json、application/x-www-form-urlencoded, multipart/form-data, text/xml,其中application/json 是近年來最常用的一種。下面簡(jiǎn)單介紹每種格式。

JSON數(shù)據(jù)格式

application/json 通常是HttpClient發(fā)送JSON格式的數(shù)據(jù),通過使用HttpContent的StringContent并設(shè)置其MediaType為"application/json"。
示例:
using Newtonsoft.Json;using System;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;
namespace Fountain.WinConsole.HttpDemo{    internal class Program    {        static async Task Main(string[] args)        {            try            {                using (HttpClient httpClient = new HttpClient())                {                    User user = new User();                    user.username = "test";                    user.password = "123456";                    string jsonData = JsonConvert.SerializeObject(user);                    // 發(fā)送請(qǐng)求數(shù)據(jù)包                    StringContent content = new StringContent(jsonData, Encoding.UTF8);                    // 設(shè)置HTTP 響應(yīng)上的ContentType --application/json                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");                    // 請(qǐng)求訪問地址                    string url = "https://127.0.0.1/api/user/login";                    // 發(fā)出HTTP的Post請(qǐng)求                    HttpResponseMessage response = await httpClient.PostAsync(url, content);                    // 讀取返回結(jié)果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 將字符轉(zhuǎn)對(duì)象                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

表單數(shù)據(jù)格式

application/x-www-form-urlencoded 這種格式通常用于表單數(shù)據(jù)的提交,通過使用HttpContent的FormUrlEncodedContent 類定義實(shí)現(xiàn)。
示例:
using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System;using System.Collections;using System.Collections.Generic;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;
namespace Fountain.WinConsole.HttpDemo{    internal class Program    {        static async Task Main(string[] args)        {            try            {                using (HttpClient httpClient = new HttpClient())                {                    Dictionary<string,string> user = new Dictionary<string, string>                    {                        { "username", "test" },                        { "password", "123456" }                    };                    // 發(fā)送請(qǐng)求數(shù)據(jù)包                    FormUrlEncodedContent content = new FormUrlEncodedContent(user);                    // 請(qǐng)求訪問地址                    string url = "https://127.0.0.1/api/user/login";                    // 發(fā)出HTTP的Post請(qǐng)求                    HttpResponseMessage response = await httpClient.PostAsync(url, content);                    // 讀取返回結(jié)果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 將字符轉(zhuǎn)對(duì)象                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

文件上傳格式

multipart/form-data 常用于文件上傳的數(shù)據(jù)格式,通過用MultipartFormDataContent類定義實(shí)現(xiàn)。
示例:
using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;
namespace Fountain.WinConsole.HttpDemo{    internal class Program    {        static async Task Main(string[] args)        {            try            {                using (HttpClient httpClient = new HttpClient())                {                    MultipartFormDataContent multipartContent = new MultipartFormDataContent();                    multipartContent.Add(new StringContent("user"), "test");                    multipartContent.Add(new ByteArrayContent(File.ReadAllBytes(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "test.jpg"))), "image", "test.jpg");                    // 請(qǐng)求訪問地址                    string url = "https://127.0.0.1/api/user/upload";                    // 發(fā)出HTTP的Post請(qǐng)求                    HttpResponseMessage response = await httpClient.PostAsync(url, multipartContent);                    // 讀取返回結(jié)果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 將字符轉(zhuǎn)對(duì)象                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

XML數(shù)據(jù)格式

text/xml 主要用于傳輸XML格式的數(shù)據(jù),通過使用HttpContent 中的StringContent并設(shè)置其MediaType為"text/xml"。
示例:
using Newtonsoft.Json;using Newtonsoft.Json.Linq;using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;
namespace Fountain.WinConsole.HttpDemo{    internal class Program    {        static async Task Main(string[] args)        {            try            {                using (HttpClient httpClient = new HttpClient())                {                    StringBuilder user = new StringBuilder();                    user.AppendLine("<usrname>test</usrname>");                    user.AppendLine("<password>test123456</password>");                    string xmlData = user.ToString();                    // 發(fā)送請(qǐng)求數(shù)據(jù)包                    StringContent content = new StringContent(xmlData, Encoding.UTF8);                    // 設(shè)置HTTP 響應(yīng)上的ContentType --text/xml                    content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");                    // 請(qǐng)求訪問地址                    string url = "https://127.0.0.1/api/user/login";                    // 發(fā)出HTTP的Post請(qǐng)求                    HttpResponseMessage response = await httpClient.PostAsync(url, content);                    // 讀取返回結(jié)果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 將字符轉(zhuǎn)對(duì)象                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

小結(jié)

以上是C#在使用HttpClient類發(fā)起 HTTP 的Post請(qǐng)求時(shí),使用四種數(shù)據(jù)格式的方式。希望對(duì)各位有所幫助。如有不到之處,請(qǐng)多多包涵。


該文章在 2024/6/8 18:15:51 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點(diǎn)晴ERP是一款針對(duì)中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國(guó)內(nèi)大量中小企業(yè)的青睞。
點(diǎn)晴PMS碼頭管理系統(tǒng)主要針對(duì)港口碼頭集裝箱與散貨日常運(yùn)作、調(diào)度、堆場(chǎng)、車隊(duì)、財(cái)務(wù)費(fèi)用、相關(guān)報(bào)表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點(diǎn),圍繞調(diào)度、堆場(chǎng)作業(yè)而開發(fā)的。集技術(shù)的先進(jìn)性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點(diǎn)晴WMS倉儲(chǔ)管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲(chǔ)管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號(hào)管理軟件。
點(diǎn)晴免費(fèi)OA是一款軟件和通用服務(wù)都免費(fèi),不限功能、不限時(shí)間、不限用戶的免費(fèi)OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved

主站蜘蛛池模板: 99久久久精品免费 | 国产在线拍揄自揄视精品不卡 | 成人亚洲精品 | 国产av无码专区亚洲av毛网站 | 成人免费aⅴ视频一区二区 成人免费aa片 | 97精品国产自产在线观看 | 东京热无码中文字幕av专区 | 国产专区第一页在线看 | 国产激情无码一区二区app | 国产午夜精品一二区 | 国产精品欧美极品中文久久 | 国产精品入口 | 国产精品专区第1页 | 国产蜜臀在线观看 | 国产成人免 | 国产成人精品一区二区免费 | 国产无码免费在线观看网站 | 精品国产黑色丝袜高跟鞋 | 成人午夜视频在线观看免费 | 国产经典自拍视频在 | 国产激情视频在线观看 | 99久久精品国产波多野结衣 | 国产精品乱 | 2025无码专区人妻系列日韩 | 国产亚洲成a人片在线观看 国产亚洲成v人片在线观黄桃 | 国产午夜福利精品无码 | 国产精品国产午夜免费 | 国产成人亚洲精品乱码在线观看 | 国产精品va在线观看无码电影麻豆 | 韩国美女跳舞蹈视频 | 国产三级精品美女三级 | 国产精品入口免费麻豆 | av无码亚州不卡播放网点 | 国产后入清纯学生妹 | 国产精品高清无码在线观看 | 国产精品丝袜亚洲熟女 | 国产精品重口变态sm在线观看 | 高清在线一区二区三区 | 91无码人妻精| 97人妻天天爽夜夜爽二区 | 东京热一精品无码av |