淺析C#中不同格式請(qǐng)求的區(qū)別
一 區(qū)分
form-data 請(qǐng)求和 x-www-form-urlencoded 請(qǐng)求是兩種常見的 HTTP 請(qǐng)求體格式。
form-data 請(qǐng)求:
form-data請(qǐng)求常用于上傳文件或二進(jìn)制數(shù)據(jù)。它使用一種鍵值對(duì)的形式構(gòu)建請(qǐng)求體,每個(gè)字段都有自己的唯一標(biāo)識(shí)符和值。- 在
form-data請(qǐng)求中,每個(gè)字段都會(huì)包含一個(gè)額外的頭部信息來描述字段的內(nèi)容類型(Content-Type)和其他屬性,例如文件名、文件類型等。 - 該請(qǐng)求體格式適合用于上傳文件或包含大量二進(jìn)制數(shù)據(jù)的情況。
x-www-form-urlencoded 請(qǐng)求:
x-www-form-urlencoded請(qǐng)求主要用于提交表單數(shù)據(jù)。它將請(qǐng)求參數(shù)作為 URL 的查詢字符串添加到請(qǐng)求體中。- 在
x-www-form-urlencoded格式中,請(qǐng)求參數(shù)以鍵值對(duì)的形式出現(xiàn),并且通過特殊字符進(jìn)行編碼,例如將空格編碼為 "+" 或 "%20",將特殊字符編碼為 "%XX" 形式。 - 這種請(qǐng)求體格式通常用于發(fā)送較小的文本數(shù)據(jù),并且可以通過 GET 或 POST 請(qǐng)求發(fā)送。
總結(jié):
form-data適合用于上傳文件或二進(jìn)制數(shù)據(jù),每個(gè)字段都帶有頭部信息;x-www-form-urlencoded適合提交表單數(shù)據(jù),參數(shù)以鍵值對(duì)的形式出現(xiàn)并進(jìn)行編碼。
選擇使用哪種格式需要根據(jù)具體的需求和服務(wù)器端的要求來決定。通常,Web 表單會(huì)使用 x-www-form-urlencoded 格式,而文件上傳則使用 form-data 格式。
通常我們請(qǐng)求的格式都是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; // 設(shè)置超時(shí)時(shí)間
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>
/// 設(shè)置證書策略
/// </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;
}
}
}
// 對(duì)轉(zhuǎn)碼后的字符進(jìn)行大寫轉(zhuǎn)換,不會(huì)把參數(shù)轉(zhuǎn)換成大寫
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;
}但是對(duì)應(yīng)x-www-form-urlencoded 的是行不通的,于是用gpt平臺(tái)提供的方法和自己改造有了下面這個(gè)方法
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; // 設(shè)置超時(shí)時(shí)間
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 + ":簽名結(jié)果:" + newsign + " \r\n 請(qǐng)求結(jié)果responseBody:" + responseBody);
}二 擴(kuò)展學(xué)習(xí)
form-data C#如何寫請(qǐng)求代碼? gpt平臺(tái)回答
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())
{
// 構(gòu)建請(qǐng)求體
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 請(qǐng)求并獲取響應(yīng)
HttpResponseMessage response = await httpClient.PostAsync("http://example.com", formDataContent);
// 確保請(qǐng)求成功
response.EnsureSuccessStatusCode();
// 處理響應(yīng)數(shù)據(jù)...
}
}
}在上述代碼中,我們首先創(chuàng)建了一個(gè) MultipartFormDataContent 實(shí)例,用于構(gòu)建 form-data 請(qǐng)求體。
然后,我們使用 Add 方法添加了兩個(gè)表單字段。每個(gè)字段都由一個(gè) StringContent 對(duì)象表示,第一個(gè)參數(shù)傳遞字段的值,第二個(gè)參數(shù)傳遞字段的名稱。
接下來,我們使用 Add 方法添加了一個(gè)文件字段。首先,我們將文件讀取為字節(jié)數(shù)組,然后使用 ByteArrayContent 將其封裝為請(qǐng)求體的一部分。第一個(gè)參數(shù)是字節(jié)數(shù)組,第二個(gè)參數(shù)是文件字段的名稱,第三個(gè)參數(shù)是文件名。
最后,我們使用 PostAsync 方法發(fā)送 POST 請(qǐng)求,并將構(gòu)建的 MultipartFormDataContent 對(duì)象作為請(qǐng)求體的參數(shù)傳遞。
請(qǐng)注意,根據(jù)實(shí)際需求,您需要修改代碼中的字段內(nèi)容、文件路徑和請(qǐng)求的目標(biāo) URL。
C#如何用HttpWebRequest 實(shí)現(xiàn)x-www-form-urlencoded格式的請(qǐng)求? gpt平臺(tái)回答
using System;
using System.IO;
using System.Net;
using System.Text;
public class Program
{
public static void Main()
{
// 請(qǐng)求的目標(biāo) URL
string url = "http://example.com";
// 構(gòu)建請(qǐng)求參數(shù)(鍵值對(duì)形式)
string requestData = "field1=value1&field2=value2";
// 將請(qǐng)求參數(shù)轉(zhuǎn)換為字節(jié)數(shù)組
byte[] requestDataBytes = Encoding.UTF8.GetBytes(requestData);
// 創(chuàng)建 HttpWebRequest 對(duì)象并設(shè)置請(qǐng)求方法和請(qǐng)求頭
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// 設(shè)置請(qǐng)求體長(zhǎng)度
request.ContentLength = requestDataBytes.Length;
try
{
// 寫入請(qǐng)求體數(shù)據(jù)
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(requestDataBytes, 0, requestDataBytes.Length);
}
// 發(fā)送請(qǐng)求并獲取響應(yīng)
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// 處理響應(yīng)...
Console.WriteLine("Response status: " + response.StatusCode);
}
}
catch (WebException ex)
{
// 處理錯(cuò)誤情況...
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}在上述代碼中,我們首先構(gòu)建了要發(fā)送的請(qǐng)求參數(shù) requestData,以鍵值對(duì)的形式表示。將請(qǐng)求參數(shù)轉(zhuǎn)換為字節(jié)數(shù)組 requestDataBytes。
然后,我們創(chuàng)建了 HttpWebRequest 對(duì)象,并設(shè)置請(qǐng)求的 URL、請(qǐng)求方法為 "POST",以及請(qǐng)求頭中的 Content-Type 為 "application/x-www-form-urlencoded"。
接下來,我們?cè)O(shè)置請(qǐng)求的內(nèi)容長(zhǎng)度 ContentLength,將其設(shè)置為請(qǐng)求體字節(jié)數(shù)組的長(zhǎng)度。
然后,我們使用 GetRequestStream 方法獲取請(qǐng)求的輸出流,并將請(qǐng)求體數(shù)據(jù)寫入該流中,即寫入請(qǐng)求的內(nèi)容。
最后,我們發(fā)送請(qǐng)求,并使用 GetResponse 方法獲取響應(yīng)。在此示例中,我們僅打印了響應(yīng)的狀態(tài)碼。
總結(jié)
還是自己知識(shí)太欠缺了,需要多多學(xué)習(xí),補(bǔ)充知識(shí)。 請(qǐng)求格式真的很多,在postman 中發(fā)現(xiàn)有這些。

到此這篇關(guān)于淺析C#中不同格式請(qǐng)求的區(qū)別的文章就介紹到這了,更多相關(guān)C#請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
WPF實(shí)現(xiàn)類似360安全衛(wèi)士界面的程序源碼分享
最近在網(wǎng)上看到了新版的360安全衛(wèi)士,感覺界面還不錯(cuò),于是用WPF制作了一個(gè),時(shí)間有限,一些具體的控件沒有制作,用圖片代替了。感興趣的朋友一起跟著小編學(xué)習(xí)WPF實(shí)現(xiàn)類似360安全衛(wèi)士界面的程序源碼分享2015-09-09
C#調(diào)用WinAPI部分命令的方法實(shí)現(xiàn)
本文主要介紹了C#調(diào)用WinAPI部分命令的方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-01-01
C#實(shí)現(xiàn)Winform監(jiān)控文件夾變化以及監(jiān)控文件操作教程
在開發(fā)應(yīng)用程序時(shí),我們可能會(huì)因?yàn)閳?chǎng)景的需要,要對(duì)文件系統(tǒng)中的文件或文件夾進(jìn)行實(shí)時(shí)監(jiān)測(cè),以便在文件內(nèi)容改變、文件被創(chuàng)建、刪除或重命名時(shí)能夠及時(shí)做出反應(yīng),今天,我將為大家介紹完整的操作流程,讓你輕松實(shí)現(xiàn)監(jiān)控文件/文件夾變化的功能,需要的朋友可以參考下2024-12-12
C#實(shí)現(xiàn)功能強(qiáng)大的中國(guó)農(nóng)歷日歷操作類
這篇文章主要介紹了C#實(shí)現(xiàn)功能強(qiáng)大的中國(guó)農(nóng)歷日歷操作類,實(shí)例分析了C#操作時(shí)間及字符串的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-03-03

