当前位置:网站首页>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();
}
}边栏推荐
- 复选框的使用:全选,全不选,选一部分
- Pat class B common function Usage Summary
- Three. JS local environment setup
- Segmentation fault occurs during VFORK execution
- ComponentScan和ComponentScans的区别
- Model transformation onnx2engine
- Application of derivative in daily question
- C# WebRequest POST模式 ,基于“Basic Auth”口令认证模式,使用multipart/form-data方式上传文件及提交其他数据
- The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
- softmax的近似之NCE详解
猜你喜欢

Vs 2019 configure tensorrt to generate engine
![MySQL practice 45 lecture [transaction isolation]](/img/a5/5420651d6be51e892976f02be8c43c.png)
MySQL practice 45 lecture [transaction isolation]

力扣------网格中的最小路径代价

分布式事务

Docker install redis

el-tree搜索方法使用

一文带你了解 ZigBee
![MySQL Real combat 45 [SQL query and Update Execution Process]](/img/cd/3a635f0c3bb4ac3c8241cb77285cc8.png)
MySQL Real combat 45 [SQL query and Update Execution Process]

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

The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
随机推荐
docker安装mysql
VS code配置虚拟环境
Do you really understand relays?
二维数组中的元素求其存储地址
[C language] MD5 encryption for account password
About HTTP cache control
umi 路由拦截(简单粗暴)
New programmers use the isXXX form to define Boolean types in the morning, and are discouraged in the afternoon?
How to make backgroundworker return an object
Vs 2019 configure tensorrt to generate engine
模糊查詢時報錯Parameter index out of range (1 > number of parameters, which is 0)
[combinatorics] Application of exponential generating function (multiple set arrangement problem | different balls in different boxes | derivation of exponential generating function of odd / even sequ
MySQL Real combat 45 [SQL query and Update Execution Process]
文件重命名
I2C 子系统(四):I2C debug
3D drawing example
How do you adjust the scope of activerecord Association in rails 3- How do you scope ActiveRecord associations in Rails 3?
What happens between entering the URL and displaying the page?
Segmentation fault occurs during VFORK execution
【PyG】理解MessagePassing过程,GCN demo详解