淺析C#中不同格式請求的區(qū)別
一 區(qū)分
form-data
請求和 x-www-form-urlencoded
請求是兩種常見的 HTTP 請求體格式。
form-data
請求:
form-data
請求常用于上傳文件或二進制數(shù)據(jù)。它使用一種鍵值對的形式構建請求體,每個字段都有自己的唯一標識符和值。- 在
form-data
請求中,每個字段都會包含一個額外的頭部信息來描述字段的內(nèi)容類型(Content-Type)和其他屬性,例如文件名、文件類型等。 - 該請求體格式適合用于上傳文件或包含大量二進制數(shù)據(jù)的情況。
x-www-form-urlencoded
請求:
x-www-form-urlencoded
請求主要用于提交表單數(shù)據(jù)。它將請求參數(shù)作為 URL 的查詢字符串添加到請求體中。- 在
x-www-form-urlencoded
格式中,請求參數(shù)以鍵值對的形式出現(xiàn),并且通過特殊字符進行編碼,例如將空格編碼為 "+" 或 "%20",將特殊字符編碼為 "%XX" 形式。 - 這種請求體格式通常用于發(fā)送較小的文本數(shù)據(jù),并且可以通過 GET 或 POST 請求發(fā)送。
總結:
form-data
適合用于上傳文件或二進制數(shù)據(jù),每個字段都帶有頭部信息;x-www-form-urlencoded
適合提交表單數(shù)據(jù),參數(shù)以鍵值對的形式出現(xiàn)并進行編碼。
選擇使用哪種格式需要根據(jù)具體的需求和服務器端的要求來決定。通常,Web 表單會使用 x-www-form-urlencoded
格式,而文件上傳則使用 form-data
格式。
通常我們請求的格式都是json 字符串,直接使用下面的方法是可以的
public static string SendHttpRequest2(string url, string Body = "", string contentType = null, Dictionary<string, string> headers = null, int Timeout = 30) { byte[] sendData = Encoding.UTF8.GetBytes(Body); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Timeout = Timeout; // 設置超時時間 if (contentType != null) { request.ContentType = contentType; } if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } using (Stream sendStream = request.GetRequestStream()) { sendStream.Write(sendData, 0, sendData.Length); sendStream.Close(); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); return reader.ReadToEnd(); } } }
或者
/// <summary> /// 設置證書策略 /// </summary> public static void SetCertificatePolicy() { System.Net.ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate; } /// <summary> /// Remotes the certificate validate. /// </summary> private static bool RemoteCertificateValidate( object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { return true; } public static string HttpPost(string url, string body = null, string contentType = null, int timeOut = 3000) { // body = body ?? ""; SetCertificatePolicy(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, timeOut); using (HttpContent httpContent = new StringContent(UrlEncodeToJava(body), Encoding.UTF8)) { if (contentType != null) httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = client.PostAsync(url, httpContent).Result; return response.Content.ReadAsStringAsync().Result; } } } // 對轉碼后的字符進行大寫轉換,不會把參數(shù)轉換成大寫 public static string UrlEncodeToJava(string source) { StringBuilder builder = new StringBuilder(); foreach (char c in source) { if (HttpUtility.UrlEncode(c.ToString(), Encoding.UTF8).Length > 1) { builder.Append(HttpUtility.UrlEncode(c.ToString(), Encoding.UTF8).ToUpper()); } else { builder.Append(c); } } string encodeUrl = builder.ToString().Replace("(", "%28").Replace(")", "%29"); return encodeUrl; }
但是對應x-www-form-urlencoded
的是行不通的,于是用gpt平臺提供的方法和自己改造有了下面這個方法
public static string HttpPost(string url, SortedDictionary<string, string> dictionary, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 3000) { using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, timeOut); if (headers != null) { foreach (var header in headers) { client.DefaultRequestHeaders.Add(header.Key, header.Value); } } using (HttpContent httpContent = new FormUrlEncodedContent(dictionary)) { if (contentType != null) httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = client.PostAsync(url, httpContent).Result; return response.Content.ReadAsStringAsync().Result; } } }
也可以使用 SendHttpRequest2
/// <summary> /// 同步方法 /// </summary> /// <param name="url"></param> /// <param name="Timeout"></param> /// <param name="method"></param> /// <returns></returns> public static string SendHttpRequest2(string url, string Body = "", string contentType = null, Dictionary<string, string> headers = null, int Timeout = 30) { byte[] sendData = Encoding.UTF8.GetBytes(Body); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Timeout = Timeout; // 設置超時時間 if (contentType != null) { request.ContentType = contentType; } if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } // request.Headers.Add("app_id", "NTEST"); // request.Headers.Add("app_key", "eef7b688-19c4-433b-94f1-300523964f2f"); using (Stream sendStream = request.GetRequestStream()) { sendStream.Write(sendData, 0, sendData.Length); sendStream.Close(); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); return reader.ReadToEnd(); } } }
參數(shù)處理成url方式
[HttpPost] public ActionResult TestCaiNiao() { string logistics_interface = Request["logistics_interface"]; string nonce = Request["nonce"]; string sign = Request["sign"]; CaiNiaoService caiNiaoServeoce = new CaiNiaoService(); SortedDictionary<string, string> dictionary = new SortedDictionary<string, string>(); TestModel3 test3 = JsonConvert.DeserializeObject<TestModel3>(logistics_interface); string logistics_interface2 = JsonConvert.SerializeObject(test3); dictionary.Add("logistics_test", logistics_interface2); dictionary.Add("nonce", nonce); dictionary.Add("sign", sign); string newsign = caiNiaoServeoce.GetCommonSign222(dictionary); dictionary.Add("sign", sign); string responseBody = ""; string url = "https://testxxxxxx"; Dictionary<string, string> headers = new Dictionary<string,string>(); headers.Add("appId", "testdemo"); // responseBody = HttpHelperService.HttpPost(url, dictionary, "application/x-www-form-urlencoded", headers, 3000); string body = ""; int i = 1; foreach (var item in dictionary) { if(i==dictionary.Count) { body += item.Key + "=" + item.Value; } else { body += item.Key + "=" + item.Value + "&"; } i++; } responseBody = HttpHelperService.SendHttpRequest2(url, body, "application/x-www-form-urlencoded", headers, 3000); return Content(sign + ":簽名結果:" + newsign + " \r\n 請求結果responseBody:" + responseBody); }
二 擴展學習
form-data C#如何寫請求代碼? gpt平臺回答
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; public class Program { public static async Task Main() { using (var httpClient = new HttpClient()) { // 構建請求體 var formDataContent = new MultipartFormDataContent(); // 添加表單字段 formDataContent.Add(new StringContent("value1"), "field1"); formDataContent.Add(new StringContent("value2"), "field2"); // 添加文件字段 var fileBytes = await System.IO.File.ReadAllBytesAsync("path/to/file.txt"); var fileContent = new ByteArrayContent(fileBytes); formDataContent.Add(fileContent, "fileField", "file.txt"); // 發(fā)送 POST 請求并獲取響應 HttpResponseMessage response = await httpClient.PostAsync("http://example.com", formDataContent); // 確保請求成功 response.EnsureSuccessStatusCode(); // 處理響應數(shù)據(jù)... } } }
在上述代碼中,我們首先創(chuàng)建了一個 MultipartFormDataContent
實例,用于構建 form-data
請求體。
然后,我們使用 Add
方法添加了兩個表單字段。每個字段都由一個 StringContent
對象表示,第一個參數(shù)傳遞字段的值,第二個參數(shù)傳遞字段的名稱。
接下來,我們使用 Add
方法添加了一個文件字段。首先,我們將文件讀取為字節(jié)數(shù)組,然后使用 ByteArrayContent
將其封裝為請求體的一部分。第一個參數(shù)是字節(jié)數(shù)組,第二個參數(shù)是文件字段的名稱,第三個參數(shù)是文件名。
最后,我們使用 PostAsync
方法發(fā)送 POST 請求,并將構建的 MultipartFormDataContent
對象作為請求體的參數(shù)傳遞。
請注意,根據(jù)實際需求,您需要修改代碼中的字段內(nèi)容、文件路徑和請求的目標 URL。
C#如何用HttpWebRequest 實現(xiàn)x-www-form-urlencoded格式的請求? gpt平臺回答
using System; using System.IO; using System.Net; using System.Text; public class Program { public static void Main() { // 請求的目標 URL string url = "http://example.com"; // 構建請求參數(shù)(鍵值對形式) string requestData = "field1=value1&field2=value2"; // 將請求參數(shù)轉換為字節(jié)數(shù)組 byte[] requestDataBytes = Encoding.UTF8.GetBytes(requestData); // 創(chuàng)建 HttpWebRequest 對象并設置請求方法和請求頭 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; // 設置請求體長度 request.ContentLength = requestDataBytes.Length; try { // 寫入請求體數(shù)據(jù) using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(requestDataBytes, 0, requestDataBytes.Length); } // 發(fā)送請求并獲取響應 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { // 處理響應... Console.WriteLine("Response status: " + response.StatusCode); } } catch (WebException ex) { // 處理錯誤情況... Console.WriteLine("An error occurred: " + ex.Message); } } }
在上述代碼中,我們首先構建了要發(fā)送的請求參數(shù) requestData
,以鍵值對的形式表示。將請求參數(shù)轉換為字節(jié)數(shù)組 requestDataBytes
。
然后,我們創(chuàng)建了 HttpWebRequest
對象,并設置請求的 URL、請求方法為 "POST",以及請求頭中的 Content-Type 為 "application/x-www-form-urlencoded"。
接下來,我們設置請求的內(nèi)容長度 ContentLength
,將其設置為請求體字節(jié)數(shù)組的長度。
然后,我們使用 GetRequestStream
方法獲取請求的輸出流,并將請求體數(shù)據(jù)寫入該流中,即寫入請求的內(nèi)容。
最后,我們發(fā)送請求,并使用 GetResponse
方法獲取響應。在此示例中,我們僅打印了響應的狀態(tài)碼。
總結
還是自己知識太欠缺了,需要多多學習,補充知識。 請求格式真的很多,在postman 中發(fā)現(xiàn)有這些。
到此這篇關于淺析C#中不同格式請求的區(qū)別的文章就介紹到這了,更多相關C#請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
WPF實現(xiàn)類似360安全衛(wèi)士界面的程序源碼分享
最近在網(wǎng)上看到了新版的360安全衛(wèi)士,感覺界面還不錯,于是用WPF制作了一個,時間有限,一些具體的控件沒有制作,用圖片代替了。感興趣的朋友一起跟著小編學習WPF實現(xiàn)類似360安全衛(wèi)士界面的程序源碼分享2015-09-09C#調(diào)用WinAPI部分命令的方法實現(xiàn)
本文主要介紹了C#調(diào)用WinAPI部分命令的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-01-01C#實現(xiàn)Winform監(jiān)控文件夾變化以及監(jiān)控文件操作教程
在開發(fā)應用程序時,我們可能會因為場景的需要,要對文件系統(tǒng)中的文件或文件夾進行實時監(jiān)測,以便在文件內(nèi)容改變、文件被創(chuàng)建、刪除或重命名時能夠及時做出反應,今天,我將為大家介紹完整的操作流程,讓你輕松實現(xiàn)監(jiān)控文件/文件夾變化的功能,需要的朋友可以參考下2024-12-12C#實現(xiàn)功能強大的中國農(nóng)歷日歷操作類
這篇文章主要介紹了C#實現(xiàn)功能強大的中國農(nóng)歷日歷操作類,實例分析了C#操作時間及字符串的技巧,非常具有實用價值,需要的朋友可以參考下2015-03-03