C# HttpWebRequest post 数据与上传图片到server

主体

            Dictionary<string, object> postData = new Dictionary<string, object>();           string fileFullPath = this.imgFullPath;if (!File.Exists(fileFullPath)){Message(Error, "file not exist: " + fileFullPath);goto EndGetPost;}// 先定义一个byte数组// 将指定的文件数据读取到 数组中byte[] bFile = null;// path是文件的路径using (FileStream fs = new FileStream(fileFullPath, FileMode.Open)){// 定义这个byte[]数组的长度 为文件的lengthbFile = new byte[fs.Length];// 把fs文件读入到arrFile数组中,0是指偏移量,从0开始读,arrFile.length是指需要读的长度,也就是整个文件的长度fs.Read(bFile, 0, bFile.Length);}postData.Add("file", new FileParameter(bFile, fileFullPath, "image/jpg"));//--------------------------------------// Create request and receive responsestring postURL = this.url;string userAgent = "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);// Process responseStreamReader responseReader = new StreamReader(webResponse.GetResponseStream());fullResponse = responseReader.ReadToEnd();responseReader.Close();webResponse.Close();

 /// <summary>/// 表单数据项./// </summary>public static class FormUpload{private static readonly Encoding ENCODING = Encoding.UTF8;/// <summary>/// MultipartFormDataPost./// </summary>/// <param name="postUrl">.</param>/// <param name="userAgent">string.</param>/// <param name="postParameters">send.</param>/// <returns>HttpWebResponse.</returns>public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters){string formDataBoundary = string.Format("----------{0:N}", Guid.NewGuid());string contentType = "multipart/form-data; boundary=" + formDataBoundary;byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);return PostForm(postUrl, userAgent, contentType, formData);}/// <summary>/// send to api./// </summary>/// <param name="postUrl">url.</param>/// <param name="userAgent">string agent.</param>/// <param name="contentType">send type.</param>/// <param name="formData">type.</param>/// <returns>HttpWebResponse.</returns>private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData){// use https or http// HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;HttpWebRequest request = null;if (postUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase)){Message(Warning, "use https:-------");request = WebRequest.Create(postUrl) as HttpWebRequest;ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);request.ProtocolVersion = HttpVersion.Version11;// 这里设置了协议类型。// SecurityProtocolType.Tls1.2;ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;request.KeepAlive = false;ServicePointManager.CheckCertificateRevocationList = true;ServicePointManager.DefaultConnectionLimit = 100;ServicePointManager.Expect100Continue = false;}else{Message(Warning, "use http default");request = (HttpWebRequest)WebRequest.Create(postUrl);}// start -------if (request == null){throw new NullReferenceException("request is not a http request");}// Set up the request properties.request.Method = "POST";request.ContentType = contentType;request.UserAgent = userAgent;request.CookieContainer = new CookieContainer();request.ContentLength = formData.Length;request.Accept = "application/json";// You could add authentication here as well if needed:// request.PreAuthenticate = true;// request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;// request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));// Send the form data to the request.using (Stream requestStream = request.GetRequestStream()){requestStream.Write(formData, 0, formData.Length);requestStream.Close();}return request.GetResponse() as HttpWebResponse;}private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary){Stream formDataStream = new System.IO.MemoryStream();bool needsCLRF = false;foreach (var param in postParameters){// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.// Skip it on the first parameter, add it to subsequent parameters.if (needsCLRF){formDataStream.Write(ENCODING.GetBytes("\r\n"), 0, ENCODING.GetByteCount("\r\n"));}needsCLRF = true;if (param.Value is FileParameter){FileParameter fileToUpload = (FileParameter)param.Value;// Add just the first part of this param, since we will write the file data directly to the Streamstring header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",boundary,param.Key,fileToUpload.FileName ?? param.Key,fileToUpload.ContentType ?? "application/octet-stream");formDataStream.Write(ENCODING.GetBytes(header), 0, ENCODING.GetByteCount(header));// Write the file data directly to the Stream, rather than serializing it to a string.formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);}else{string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",boundary,param.Key,param.Value);formDataStream.Write(ENCODING.GetBytes(postData), 0, ENCODING.GetByteCount(postData));}}// Add the end of the request.  Start with a newlinestring footer = "\r\n--" + boundary + "--\r\n";formDataStream.Write(ENCODING.GetBytes(footer), 0, ENCODING.GetByteCount(footer));// Dump the Stream into a byte[]formDataStream.Position = 0;byte[] formData = new byte[formDataStream.Length];formDataStream.Read(formData, 0, formData.Length);formDataStream.Close();return formData;}/// <summary>/// CheckValidationResult./// </summary>/// <param name="sender">sender.</param>/// <param name="certificate">certificate.</param>/// <param name="chain">chain.</param>/// <param name="errors">errors.</param>/// <returns>true.</returns>private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors){// 总是接受return true;}}/// <summary>/// FileParameter./// </summary>public class FileParameter{/// <summary>/// Initializes a new instance of the <see cref="FileParameter"/> class./// FileParameter./// </summary>/// <param name="file">file.</param>/// <param name="filename">filename.</param>/// <param name="contenttype">contenttype.</param>public FileParameter(byte[] file, string filename, string contenttype){this.File = file;this.FileName = filename;this.ContentType = contenttype;}/// <summary>/// Gets or sets File./// </summary>public byte[] File { get; set; }/// <summary>/// Gets or sets FileName./// </summary>public string FileName { get; set; }/// <summary>/// Gets or sets ContentType./// </summary>public string ContentType { get; set; }}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280862.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

多亏了Google相册,如何一键释放Android手机上的空间

Let’s be real here: modern smartphones have limited storage. While they’re coming with a lot more than they used to, it’s easy to fill 32GB without even realizing it. And with today’s high-end cameras, well, pictures and videos can quickly consume a bi…

用window.location.href实现页面跳转

在写ASP.Net程序的时候&#xff0c;我们经常遇到跳转页面的问题&#xff0c;我们经常使用Response.Redirect &#xff0c;如果客户要在跳转的时候使用提示&#xff0c;这个就不灵光了&#xff0c;如&#xff1a;Response.Write("<script>alert(恭喜您&#xff0c;注…

(一)使用appium之前为什么要安装nodejs???

很多人在刚接触appium自动化时&#xff0c;可能会像我一样&#xff0c;按照教程搭建好环境后&#xff0c;却不知道使用appium之前为什么要用到node.js&#xff0c;nodejs到底和appium是什么关系&#xff0c;对nodejs也不是很了解&#xff0c;接下来我和大家一起理解一下他们之间…

WPF效果第二百零四篇之自定义更新控件

好久没有更新文章,今天抽空来分享一下最近玩耍的自定义控件;里面包含了自定义控件、依赖属性和路由事件;来看看最终实现的效果:1、先来看看前台Xaml布局和绑定:<Style TargetType"{x:Type Cores:UploadWithProgressControl}"><Setter Property"Templat…

u3d 逐个点运动,路径运动。 U3d one by one, path motion.

u3d 逐个点运动&#xff0c;路径运动。 U3d one by one, path motion. 作者&#xff1a;韩梦飞沙 Author&#xff1a;han_meng_fei_sha 邮箱&#xff1a;313134555qq.com E-mail: 313134555 qq.com 逐个点运动&#xff0c;路径运动。 Im going to do some motion and path. 如果…

小米净水器底部漏水_漏水传感器:您可能没有的最容易被忽视的智能家居设备...

小米净水器底部漏水While most smarthome products are aimed at convenience, there’s one smarthome device that’s actually quite useful, possibly saving you headaches and ton of money: the trusty water leak sensor. 虽然大多数智能家居产品都旨在提供便利&#x…

Unity3D笔记十 游戏元素

一、地形 1.1 树元素 1.2 草元素 二、光源 2.1 点光源 点光源&#xff08;Point Light&#xff09;&#xff1a;好像包围在一个类似球形的物体中&#xff0c;读者可将球形理解为点光源的照射范围&#xff0c;就像家里的灯泡可以照亮整个屋子一样。创建点光源的方式为在Hierarch…

BZOJ3511: 土地划分

【传送门&#xff1a;BZOJ3511】 简要题意&#xff1a; 给出n个点&#xff0c;m条边&#xff0c;每个点有A和B两种形态&#xff0c;一开始1为A&#xff0c;n为B 给出VA[i]和VB[i]&#xff0c;表示第i个点选择A和B形态的价值 每条边给出x,y,EA,EB,EC&#xff0c;表示如果x和y都为…

facebook 文本分类_如何禁用和自定义Facebook的通知,文本和电子邮件

facebook 文本分类Facebook is really keen on keeping you on their platform. One of the ways they do that is by sending you notifications whenever the tiniest thing happens. And you won’t just see them on the site—Facebook will also notify you by email, wi…

django06: ORM示例2--uer 与file

存放路径&#xff1a;https://git.lug.ustc.edu.cn/ 笔记 外键与多键 path models.ForeignKey(to"Path")file models.ManyToManyField(to"File") code 处理方式 new_path request.POST.get("new_path",None)models.File.objects.create(…

Error opening terminal: xterm-256color

在使用gdb调试linux内核时&#xff0c;提示如下错误&#xff1a; arm-none-linux-gnueabi-gdb --tui vmlinux Error opening terminal: xterm-256color. 解决办法&#xff1a; 1、 edit your .bash_profile file vim .bash_profile 2、commnet #export TERMxterm-256colo…

四种简单的排序算法

四种简单的排序算法 我觉得如果想成为一名优秀的开发者&#xff0c;不仅要积极学习时下流行的新技术&#xff0c;比如WCF、Asp.Net MVC、AJAX等&#xff0c;熟练应用一些已经比较成熟的技术&#xff0c;比如Asp.Net、WinForm。还应该有着牢固的计算机基础知识&#xff0c;比如数…

Xampp修改默认端口号

为什么80%的码农都做不了架构师&#xff1f;>>> Xampp默认的端口使用如下&#xff1a; Httpd使用80端口 Httpd_ssl使用443端口 Mysql使用3306端口 ftp使用21端口 但是&#xff0c;在如上端口被占用的情况下&#xff0c;我们可以通过修改xampp默认端口的方法&…

为什么csrss进程有三个_什么是客户端服务器运行时进程(csrss.exe),为什么在我的PC上运行它?...

为什么csrss进程有三个If you have a Windows PC, open your Task Manager and you’ll definitely see one or more Client Server Runtime Process (csrss.exe) processes running on your PC. This process is an essential part of Windows. 如果您使用的是Windows PC&…

使用c#的 async/await编写 长时间运行的基于代码的工作流的 持久任务框架

持久任务框架 &#xff08;DTF&#xff09; 是基于async/await 工作流执行框架。工作流的解决方案很多&#xff0c;包括Windows Workflow Foundation&#xff0c;BizTalk&#xff0c;Logic Apps, Workflow-Core 和 Elsa-Core。最近我在Dapr 的仓库里跟踪工作流构建块的进展时&a…

bat批处理笔记

变量 1.CMD窗口变量&#xff0c;变量名必须用单%引用&#xff08;即&#xff1a;%variable&#xff09; 外部变量&#xff0c;是系统制定的&#xff0c;只有9个&#xff0c;专门保存外部参数的&#xff0c;就是运行批处理时加的参数。只有 %1 %2 %3 %4 ...... %9。 在bat内直…

多目标跟踪(MOT)论文随笔-SIMPLE ONLINE AND REALTIME TRACKING (SORT)

转载请标明链接&#xff1a;http://www.cnblogs.com/yanwei-li/p/8643336.html 网上已有很多关于MOT的文章&#xff0c;此系列仅为个人阅读随笔&#xff0c;便于初学者的共同成长。若希望详细了解&#xff0c;建议阅读原文。 本文是使用 tracking by detection 方法进行多目标…

明日大盘走势分析

如上周所述&#xff0c;大盘在4与9号双线压力下&#xff0c;上攻乏力。今天小幅下跌0.11%&#xff0c;涨511&#xff0c;平76&#xff0c;跌362&#xff0c;说明个股还是比较活跃&#xff0c;而且大盘上涨趋势未加改变&#xff0c;只是目前攻坚&#xff0c;有点缺乏外部的助力。…

android EventBus 3.0 混淆配置

2019独角兽企业重金招聘Python工程师标准>>> https://github.com/greenrobot/EventBus 使用的这个库在github的官网README中没有写明相应混淆的配置. 经过对官网的查询&#xff0c;在一个小角落还是被我找到了。 -keepattributes *Annotation* -keepclassmembers …

dotnet-exec 0.11.0 released

dotnet-exec 0.11.0 releasedIntrodotnet-exec 是一个 C# 程序的小工具&#xff0c;可以用来运行一些简单的 C# 程序而无需创建项目文件&#xff0c;让 C# 像 python/nodejs 一样简单&#xff0c;而且可以自定义项目的入口方法&#xff0c;支持但不限于 Main 方法。Install/Upd…