当前位置:网站首页>C # webrequest post mode, based on "basic auth" password authentication mode, uploads files and submits other data using multipart / form data mode
C # webrequest post mode, based on "basic auth" password authentication mode, uploads files and submits other data using multipart / form data mode
2022-07-03 03:15:00 【yc_ one thousand two hundred and twenty-four】
public class HttpClientHelper
{
const string CRLF = "\r\n";
/// <summary>
/// POST Use multipart/form-data Upload files and submit other data
/// be based on “Basic Auth” Password authentication mode
/// </summary>
/// <param name="headers"> Request header parameters </param>
/// <param name="nameValueCollection"> Key value vs. parameter </param>
/// <param name="fileCollection"> File parameters : Parameter name , File path </param>
/// <returns> Interface return result </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) Set the request 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) Set up 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);
// Deal with the content of the file
WriteFileToStream(writer, startBoundary, "file", filePath);
// Key value vs. parameter
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 Push the video file to return data :{url},{strResult}");
}
}
}
catch (Exception ex)
{
strResult = ex.Message;
MyLogger.ErrorLogger.Debug($"UploadMultipartFormData2 Error in pushing video file :{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);
// Deal with the content of the file
string[] fileKeys = fileCollection.AllKeys;
foreach (string key in fileKeys)
{
WriteFileToStream(writer, startBoundary, key, fileCollection[key]);
}
// Key value vs. parameter
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>
/// Writing documents
/// </summary>
/// <param name="writer"> flow </param>
/// <param name="startBoundary"> Start Rune </param>
/// <param name="name"> Field name </param>
/// <param name="filePath"> File address </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();
}
}
边栏推荐
- Summary of matrix knowledge points in Chapter 2 of Linear Algebra (Jeff's self perception)
- Last update time of all sqlserver tables
- I2C subsystem (III): I2C driver
- Application of derivative in daily question
- Bigvision code
- Creation and destruction of function stack frame
- Force freeing memory in PHP
- Use of El tree search method
- open file in 'w' mode: IOError: [Errno 2] No such file or directory
- Summary of determinant knowledge points in Chapter 1 of Linear Algebra (Jeff's self perception)
猜你喜欢
Why does thread crash not cause JVM crash
Vs Code configure virtual environment
Limit of one question per day
softmax的近似之NCE详解
VS code配置虚拟环境
Pytorch轻量级可视化工具wandb(local)
Anhui University | small target tracking: large-scale data sets and baselines
Thunderbolt Chrome extension caused the data returned by the server JS parsing page data exception
I2C 子系统(四):I2C debug
The series of hyperbolic function in daily problem
随机推荐
open file in 'w' mode: IOError: [Errno 2] No such file or directory
The process of connecting MySQL with docker
Hi3536C V100R001C02SPC040 交叉编译器安装
MySQL practice 45 [global lock and table lock]
I2C subsystem (I): I2C spec
基于QT的tensorRT加速的yolov5
VS 2019 配置tensorRT生成engine
The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
Idea set method call ignore case
File rename
Docker install redis
QT based tensorrt accelerated yolov5
JS finds all the parent nodes or child nodes under a node according to the tree structure
Idea format code idea set shortcut key format code
float与0比较
Opengauss database development and debugging tool guide
node 开启服务器
Vs 2019 configuration tensorrt
Nasvit: neural architecture search of efficient visual converter with gradient conflict perception hypernetwork training
C # general interface call