男女做爽爽爽网站-男女做羞羞高清-男女做爰高清无遮挡免费视频-男女做爰猛烈-男女做爰猛烈吃奶啪啪喷水网站-内射白浆一区

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

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

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

前言

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

HttpClient

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

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

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

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ā)送請求數(shù)據(jù)包                    StringContent content = new StringContent(jsonData, Encoding.UTF8);                    // 設(shè)置HTTP 響應(yīng)上的ContentType --application/json                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");                    // 請求訪問地址                    string url = "https://127.0.0.1/api/user/login";                    // 發(fā)出HTTP的Post請求                    HttpResponseMessage response = await httpClient.PostAsync(url, content);                    // 讀取返回結(jié)果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 將字符轉(zhuǎn)對象                    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 類定義實現(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ā)送請求數(shù)據(jù)包                    FormUrlEncodedContent content = new FormUrlEncodedContent(user);                    // 請求訪問地址                    string url = "https://127.0.0.1/api/user/login";                    // 發(fā)出HTTP的Post請求                    HttpResponseMessage response = await httpClient.PostAsync(url, content);                    // 讀取返回結(jié)果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 將字符轉(zhuǎn)對象                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

文件上傳格式

multipart/form-data 常用于文件上傳的數(shù)據(jù)格式,通過用MultipartFormDataContent類定義實現(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");                    // 請求訪問地址                    string url = "https://127.0.0.1/api/user/upload";                    // 發(fā)出HTTP的Post請求                    HttpResponseMessage response = await httpClient.PostAsync(url, multipartContent);                    // 讀取返回結(jié)果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 將字符轉(zhuǎn)對象                    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ā)送請求數(shù)據(jù)包                    StringContent content = new StringContent(xmlData, Encoding.UTF8);                    // 設(shè)置HTTP 響應(yīng)上的ContentType --text/xml                    content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");                    // 請求訪問地址                    string url = "https://127.0.0.1/api/user/login";                    // 發(fā)出HTTP的Post請求                    HttpResponseMessage response = await httpClient.PostAsync(url, content);                    // 讀取返回結(jié)果                    string responseContent = await response.Content.ReadAsStringAsync();                    // 將字符轉(zhuǎn)對象                    Result result = JsonConvert.DeserializeObject<Result>(responseContent);                }            }            catch (Exception exception)            {                Console.WriteLine(exception.Message);            }            Console.ReadLine();        }    }}

小結(jié)

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


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

主站蜘蛛池模板: 另类自拍 | 久久夜夜肉肉热热日日 | 精品亚洲av无码1区2区3区 | 成人黄网站A片免费观看 | H高潮嗯啊娇喘抽搐A片男男视频 | 久久久久人妻一区精品 | 欧美人妻在线视频一区二区 | 日日夜夜综合 | 国产综合久久精品东京热中 | 另类天堂| 亚洲国产欧美精品区一区二区三区 | 99久久亚洲国产精品免费 | 无码一区在线观看视频 | 亚洲av中文久久精品 | 免费无码又爽又刺激A片软软件 | 91老肥熟 | 一区成人| 日韩高清在线观看永久 | 亚洲国产欧美国产第一区二 | 内射中出无码护士在线 | 日韩在线视频www色 日韩在线视频不卡一区二区三区 | 欧美成人se01短视频在线看 | 欧美又粗又大X无码 | 亚洲国产熟妇无码一区二区三区H | 东京热中文无码 在线 | 久久毛片网站 | 日韩人妻不卡一区二区三 | 激情小说综合网 | 亚洲色无码a片一区二区 | 精品久久亚洲中文字幕 | jizz亚洲视频 | 亚洲精品久久一区二区三区四区 | 欧美精品一区二区三区免费 | 2024久久综合色播五月男人的天堂 | 一级特黄特黄的大片 | 欧美国产激情二区三区-免费A片 | 久久成人精品播放 | 无码任你躁久久久久久老妇双 | 国产91资源午夜福利 | 男女啪啪抽搐高潮动态图 | 公妇仑乱小说你yin我荡 |