当前位置:网站首页>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();
}
}边栏推荐
- Spark on yarn资源优化思路笔记
- Idea format code idea set shortcut key format code
- MySQL Real combat 45 [SQL query and Update Execution Process]
- 一文带你了解 ZigBee
- Sous - système I2C (IV): débogage I2C
- Can I use read-only to automatically implement properties- Is read-only auto-implemented property possible?
- VS 2019配置tensorRT
- 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
- The process of connecting MySQL with docker
- What happens between entering the URL and displaying the page?
猜你喜欢

C语言初阶-指针详解-庖丁解牛篇

Opengauss database development and debugging tool guide

Pat class B "1104 forever" DFS optimization idea

900W+ 数据,从 17s 到 300ms,如何操作

MySql实战45讲【索引】

Segmentation fault occurs during VFORK execution
![MySQL practice 45 [SQL query and update execution process]](/img/cd/3a635f0c3bb4ac3c8241cb77285cc8.png)
MySQL practice 45 [SQL query and update execution process]

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

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

Hi3536C V100R001C02SPC040 交叉编译器安装
随机推荐
Sqlserver row to column pivot
VS 2019配置tensorRT
The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
Model transformation onnx2engine
900W+ 数据,从 17s 到 300ms,如何操作
Use of El tree search method
How to return ordered keys after counter counts the quantity
复选框的使用:全选,全不选,选一部分
[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
45 lectures on MySQL [index]
后管中编辑与预览获取表单的值写法
Vs 2019 configuration du moteur de génération de tensorrt
[Fuhan 6630 encodes and stores videos, and uses RTSP server and timestamp synchronization to realize VLC viewing videos]
Tensorflow to pytorch notes; tf. gather_ Nd (x, y) to pytorch
@Accessors注解作用指定前缀遵守驼峰命名
用docker 连接mysql的过程
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
com.fasterxml.jackson.databind.exc.InvalidFormatException问题
内存泄漏工具VLD安装及使用
The file marked by labelme is converted to yolov5 format