当前位置:网站首页>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();
}
}
边栏推荐
- VS 2019 配置tensorRT生成engine
- LVGL使用心得
- MySql实战45讲【全局锁和表锁】
- labelimg生成的xml文件转换为voc格式
- Edit and preview in the back pipe to get the value writing method of the form
- Variable declarations following if statements
- The series of hyperbolic function in daily problem
- Elsevier latex 提交文章 pdftex.def Error: File `thumbnails/cas-email.jpeg‘ not found: using draf
- The difference between componentscan and componentscans
- Andwhere multiple or query ORM conditions in yii2
猜你喜欢
Limit of one question per day
The process of connecting MySQL with docker
MySQL practice 45 [SQL query and update execution process]
Limit of one question per day
VS code配置虚拟环境
LVGL使用心得
Why does thread crash not cause JVM crash
idea 加载不了应用市场解决办法(亲测)
Agile certification (professional scrum Master) simulation exercise-2
Pytoch configuration
随机推荐
敏捷认证(Professional Scrum Master)模拟练习题
Application of derivative in daily question
QT based tensorrt accelerated yolov5
I2C 子系统(四):I2C debug
Edit and preview in the back pipe to get the value writing method of the form
【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(一)
node 开启服务器
Docker install MySQL
I2C 子系统(一):I2C spec
一文带你了解 ZigBee
将时间戳转为指定格式的时间
The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
二维数组中的元素求其存储地址
From C to capable -- use the pointer as a function parameter to find out whether the string is a palindrome character
[mathematical logic] normal form (conjunctive normal form | disjunctive normal form | major item | minor item | maximal item | minor item | principal conjunctive normal form | principal disjunctive no
Réglez la hauteur et lancez le système. Currenttimemillis catton
Vs 2019 installation and configuration opencv
idea 加载不了应用市场解决办法(亲测)
New programmers use the isXXX form to define Boolean types in the morning, and are discouraged in the afternoon?
MySql實戰45講【SQL查詢和更新執行流程】