当前位置:网站首页>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();
}
}
边栏推荐
- The difference between componentscan and componentscans
- I2C 子系统(一):I2C spec
- I2C subsystem (II): I3C spec
- Nasvit: neural architecture search of efficient visual converter with gradient conflict perception hypernetwork training
- VS 2019 配置tensorRT生成engine
- From C to capable -- use the pointer as a function parameter to find out whether the string is a palindrome character
- [pyg] understand the messagepassing process, GCN demo details
- How to select the minimum and maximum values of columns in the data table- How to select min and max values of a column in a datatable?
- MySql实战45讲【事务隔离】
- 分布式事务
猜你喜欢
MySql实战45讲【行锁】
为什么线程崩溃不会导致 JVM 崩溃
[error record] the parameter 'can't have a value of' null 'because of its type, but the im
Unity3d RPG implementation (medium)
Spark on yarn resource optimization ideas notes
MySql实战45讲【全局锁和表锁】
左连接,内连接
C language beginner level - pointer explanation - paoding jieniu chapter
[Chongqing Guangdong education] cultural and natural heritage reference materials of China University of Geosciences (Wuhan)
Segmentation fault occurs during VFORK execution
随机推荐
MySQL practice 45 [global lock and table lock]
模糊查询时报错Parameter index out of range (1 > number of parameters, which is 0)
Process the dataset and use labelencoder to convert all IDs to start from 0
How to implement append in tensor
[shutter] monitor the transparency gradient of the scrolling action control component (remove the blank of the top status bar | frame layout component | transparency component | monitor the scrolling
How to select the minimum and maximum values of columns in the data table- How to select min and max values of a column in a datatable?
Notifydatasetchanged not applicable to recyclerview - notifydatasetchanged not working on recyclerview
I2C 子系统(二):I3C spec
labelimg生成的xml文件转换为voc格式
LVGL使用心得
Cron表达式介绍
Force freeing memory in PHP
Vs 2019 configuration du moteur de génération de tensorrt
从C到Capable-----利用指针作为函数参数求字符串是否为回文字符
C#通用接口调用
Spark on yarn资源优化思路笔记
Idea format code idea set shortcut key format code
使用InputFilter限制EditText时踩坑及解决方案
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
The file marked by labelme is converted to yolov5 format