当前位置:网站首页>C# WebRequest POST模式 ,基于“Basic Auth”口令认证模式,使用multipart/form-data方式上传文件及提交其他数据
C# WebRequest POST模式 ,基于“Basic Auth”口令认证模式,使用multipart/form-data方式上传文件及提交其他数据
2022-07-03 03:13:00 【yc_1224】
public class HttpClientHelper
{
const string CRLF = "\r\n";
/// <summary>
/// POST 使用multipart/form-data方式上传文件及提交其他数据
/// 基于“Basic Auth”口令认证模式
/// </summary>
/// <param name="headers">请求头参数</param>
/// <param name="nameValueCollection">键值对参数</param>
/// <param name="fileCollection">文件参数:参数名,文件路径</param>
/// <returns>接口返回结果</returns>
public static string UploadMultipartFormData2(string url,Dictionary<string, string> headers, NameValueCollection nameValueCollection, string userName, string passWord, string filePath)
{
var boundary = string.Format("batch_{0}", Guid.NewGuid());
var startBoundary = string.Format("--{0}", boundary);
string strResult = "";
WebRequest request = null;
try
{
// Set up Request body.
request = WebRequest.Create(url);
foreach (var item in headers)
{
request.Headers.Add(item.Key, item.Value);
}
request.Method = "POST";
//(1)设置请求Credentials
CredentialCache credentialCache = new CredentialCache
{
{ new Uri(url), "Basic", new NetworkCredential(userName, passWord) }
};
request.Credentials = credentialCache;
string Auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userName}:{passWord}"));
//(2)设置Headers Authorization
request.Headers.Add("Authorization", "Basic" + Auth);
request.ContentType = $"multipart/form-data; boundary={boundary}";
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
// 处理文件内容
WriteFileToStream(writer, startBoundary, "file", filePath);
// 键值对参数
string[] allKeys = nameValueCollection.AllKeys;
foreach (string key in allKeys)
{
WriteNvToStream(writer, startBoundary, key, nameValueCollection[key]);
}
var endFormData = CRLF + string.Format("--{0}--", boundary) + CRLF;
writer.Write(endFormData);
writer.Flush();
writer.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
strResult = reader.ReadToEnd();
MyLogger.ErrorLogger.Debug($"UploadMultipartFormData2 推送录像文件返回数据:{url},{strResult}");
}
}
}
catch (Exception ex)
{
strResult = ex.Message;
MyLogger.ErrorLogger.Debug($"UploadMultipartFormData2 推送录像文件错误:{strResult}");
return strResult;
}
finally
{
request?.Abort();
}
return strResult;
}
public static string UploadMultipartFormData(string url, Dictionary<string, string> headers, NameValueCollection nameValueCollection, NameValueCollection fileCollection)
{
var boundary = string.Format("batch_{0}", Guid.NewGuid());
var startBoundary = string.Format("--{0}", boundary);
// Set up Request body.
WebRequest request = WebRequest.Create(url);
foreach (var item in headers)
{
request.Headers.Add(item.Key, item.Value);
}
request.Method = "POST";
request.ContentType = $"multipart/form-data; boundary={boundary}";
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
// 处理文件内容
string[] fileKeys = fileCollection.AllKeys;
foreach (string key in fileKeys)
{
WriteFileToStream(writer, startBoundary, key, fileCollection[key]);
}
// 键值对参数
string[] allKeys = nameValueCollection.AllKeys;
foreach (string key in allKeys)
{
WriteNvToStream(writer, startBoundary, key, nameValueCollection[key]);
}
var endFormData = CRLF + string.Format("--{0}--", boundary) + CRLF;
writer.Write(endFormData);
writer.Flush();
writer.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
return json;
}
/// <summary>
/// 写文件
/// </summary>
/// <param name="writer">流</param>
/// <param name="startBoundary">开始符</param>
/// <param name="name">字段名</param>
/// <param name="filePath">文件地址</param>
static void WriteFileToStream(StreamWriter writer, string startBoundary, string name, string filePath)
{
var filename = Path.GetFileName(filePath);
var fileRequestBody = startBoundary + CRLF;
fileRequestBody += $"Content-Disposition: form-data; name=\"{name}\"; filename=\"{filename}\"" + CRLF + CRLF;
writer.Write(fileRequestBody);
writer.Flush();
byte[] bmpBytes = File.ReadAllBytes(filePath);
writer.BaseStream.Write(bmpBytes, 0, bmpBytes.Length);
}
static void WriteNvToStream(StreamWriter writer, string startBoundary, string name, string value)
{
var nvFormData = CRLF + startBoundary + CRLF;
nvFormData += $"Content-Disposition: form-data; name=\"{name}\"" + CRLF + CRLF;
nvFormData += value /*+ CRLF*/;
writer.Write(nvFormData);
writer.Flush();
}
}边栏推荐
- 基于Qt的yolov5工程
- Check log4j problems using stain analysis
- New programmers use the isXXX form to define Boolean types in the morning, and are discouraged in the afternoon?
- Unity3d RPG implementation (medium)
- 二维数组中的元素求其存储地址
- Thunderbolt Chrome extension caused the data returned by the server JS parsing page data exception
- node 开启服务器
- The process of connecting MySQL with docker
- labelimg生成的xml文件转换为voc格式
- Why does thread crash not cause JVM crash
猜你喜欢

TCP handshake three times and wave four times. Why does TCP need handshake three times and wave four times? TCP connection establishes a failure processing mechanism

内存泄漏工具VLD安装及使用

MySql實戰45講【SQL查詢和更新執行流程】

I2C subsystem (III): I2C driver

Do you really understand relays?

Left connection, inner connection

敏捷认证(Professional Scrum Master)模拟练习题-2

MySql实战45讲【索引】

Add automatic model generation function to hade

I2C 子系統(四):I2C debug
随机推荐
Basic information of Promethus (I)
Can I use read-only to automatically implement properties- Is read-only auto-implemented property possible?
Deep reinforcement learning for intelligent transportation systems: a survey paper reading notes
Sous - système I2C (IV): débogage I2C
Installation and use of memory leak tool VLD
Nasvit: neural architecture search of efficient visual converter with gradient conflict perception hypernetwork training
labelme标记的文件转换为yolov5格式
[Fuhan 6630 encodes and stores videos, and uses RTSP server and timestamp synchronization to realize VLC viewing videos]
Last update time of all sqlserver tables
The difference between componentscan and componentscans
将时间戳转为指定格式的时间
销毁Session和清空指定的属性
com. fasterxml. jackson. databind. Exc.invalidformatexception problem
内存泄漏工具VLD安装及使用
Idea format code idea set shortcut key format code
JS finds all the parent nodes or child nodes under a node according to the tree structure
About HTTP cache control
@Accessors annotation function specifies that the prefix follows the hump naming
程序员新人上午使用 isXxx 形式定义布尔类型,下午就被劝退?
How to use asp Net MVC identity 2 change password authentication- How To Change Password Validation in ASP. Net MVC Identity 2?