浅析C#中不同格式请求的区别
作者:大巨头
一 区分
form-data 请求和 x-www-form-urlencoded 请求是两种常见的 HTTP 请求体格式。
form-data 请求:
form-data请求常用于上传文件或二进制数据。它使用一种键值对的形式构建请求体,每个字段都有自己的唯一标识符和值。- 在
form-data请求中,每个字段都会包含一个额外的头部信息来描述字段的内容类型(Content-Type)和其他属性,例如文件名、文件类型等。 - 该请求体格式适合用于上传文件或包含大量二进制数据的情况。
x-www-form-urlencoded 请求:
x-www-form-urlencoded请求主要用于提交表单数据。它将请求参数作为 URL 的查询字符串添加到请求体中。- 在
x-www-form-urlencoded格式中,请求参数以键值对的形式出现,并且通过特殊字符进行编码,例如将空格编码为 "+" 或 "%20",将特殊字符编码为 "%XX" 形式。 - 这种请求体格式通常用于发送较小的文本数据,并且可以通过 GET 或 POST 请求发送。
总结:
form-data适合用于上传文件或二进制数据,每个字段都带有头部信息;x-www-form-urlencoded适合提交表单数据,参数以键值对的形式出现并进行编码。
选择使用哪种格式需要根据具体的需求和服务器端的要求来决定。通常,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;
}
}
}
// 对转码后的字符进行大写转换,不会把参数转换成大写
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();
}
}
}参数处理成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");
// 发送 POST 请求并获取响应
HttpResponseMessage response = await httpClient.PostAsync("http://example.com", formDataContent);
// 确保请求成功
response.EnsureSuccessStatusCode();
// 处理响应数据...
}
}
}在上述代码中,我们首先创建了一个 MultipartFormDataContent 实例,用于构建 form-data 请求体。
然后,我们使用 Add 方法添加了两个表单字段。每个字段都由一个 StringContent 对象表示,第一个参数传递字段的值,第二个参数传递字段的名称。
接下来,我们使用 Add 方法添加了一个文件字段。首先,我们将文件读取为字节数组,然后使用 ByteArrayContent 将其封装为请求体的一部分。第一个参数是字节数组,第二个参数是文件字段的名称,第三个参数是文件名。
最后,我们使用 PostAsync 方法发送 POST 请求,并将构建的 MultipartFormDataContent 对象作为请求体的参数传递。
请注意,根据实际需求,您需要修改代码中的字段内容、文件路径和请求的目标 URL。
C#如何用HttpWebRequest 实现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";
// 构建请求参数(键值对形式)
string requestData = "field1=value1&field2=value2";
// 将请求参数转换为字节数组
byte[] requestDataBytes = Encoding.UTF8.GetBytes(requestData);
// 创建 HttpWebRequest 对象并设置请求方法和请求头
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// 设置请求体长度
request.ContentLength = requestDataBytes.Length;
try
{
// 写入请求体数据
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(requestDataBytes, 0, requestDataBytes.Length);
}
// 发送请求并获取响应
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// 处理响应...
Console.WriteLine("Response status: " + response.StatusCode);
}
}
catch (WebException ex)
{
// 处理错误情况...
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}在上述代码中,我们首先构建了要发送的请求参数 requestData,以键值对的形式表示。将请求参数转换为字节数组 requestDataBytes。
然后,我们创建了 HttpWebRequest 对象,并设置请求的 URL、请求方法为 "POST",以及请求头中的 Content-Type 为 "application/x-www-form-urlencoded"。
接下来,我们设置请求的内容长度 ContentLength,将其设置为请求体字节数组的长度。
然后,我们使用 GetRequestStream 方法获取请求的输出流,并将请求体数据写入该流中,即写入请求的内容。
最后,我们发送请求,并使用 GetResponse 方法获取响应。在此示例中,我们仅打印了响应的状态码。
总结
还是自己知识太欠缺了,需要多多学习,补充知识。 请求格式真的很多,在postman 中发现有这些。

到此这篇关于浅析C#中不同格式请求的区别的文章就介绍到这了,更多相关C#请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
