WebRequest POST模式 ,基于“Basic Auth”口令认证模式,使用multipart/form-data方式上传文件及提交其他数据
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(); } }
参考资料:https://www.cnblogs.com/SherryIce/p/16195070.html
欢迎加群交流 QQ群 : 830426796