当前位置:网站首页>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();
}
}边栏推荐
- 程序员新人上午使用 isXxx 形式定义布尔类型,下午就被劝退?
- 敏捷认证(Professional Scrum Master)模拟练习题
- MySql實戰45講【SQL查詢和更新執行流程】
- What happens between entering the URL and displaying the page?
- How do you adjust the scope of activerecord Association in rails 3- How do you scope ActiveRecord associations in Rails 3?
- I2C subsystem (II): I3C spec
- 一文带你了解 ZigBee
- 模糊查询时报错Parameter index out of range (1 > number of parameters, which is 0)
- MySQL practice 45 [SQL query and update execution process]
- Why does thread crash not cause JVM crash
猜你喜欢

Left connection, inner connection

Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!

Why does thread crash not cause JVM crash

Deep reinforcement learning for intelligent transportation systems: a survey paper reading notes
![[error record] the parameter 'can't have a value of' null 'because of its type, but the im](/img/1c/46d951e2d0193999f35f14d18a2de0.jpg)
[error record] the parameter 'can't have a value of' null 'because of its type, but the im

3D drawing example

C language beginner level - pointer explanation - paoding jieniu chapter

Anhui University | small target tracking: large-scale data sets and baselines

Kubernetes family container housekeeper pod online Q & A?

敏捷认证(Professional Scrum Master)模拟练习题-2
随机推荐
@Accessors注解作用指定前缀遵守驼峰命名
解决高並發下System.currentTimeMillis卡頓
docker安装redis
Edit and preview in the back pipe to get the value writing method of the form
Are there any recommended term life insurance products? I want to buy a term life insurance.
Gavin teacher's perception of transformer live class - rasa project's actual banking financial BOT Intelligent Business Dialogue robot architecture, process and phenomenon decryption through rasa inte
I2C 子系统(一):I2C spec
VS 2019 配置tensorRT生成engine
The difference between componentscan and componentscans
Super easy to use logzero
MySQL practice 45 [global lock and table lock]
敏捷认证(Professional Scrum Master)模拟练习题-2
BigVision代码
用docker 連接mysql的過程
[pyg] understand the messagepassing process, GCN demo details
I2C subsystem (IV): I2C debug
Vs 2019 configuration du moteur de génération de tensorrt
How to use asp Net MVC identity 2 change password authentication- How To Change Password Validation in ASP. Net MVC Identity 2?
Deep learning: multi-layer perceptron and XOR problem (pytoch Implementation)
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!