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.pswp.cn/news/280862.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280862.shtml
英文地址,請注明出處:http://en.pswp.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…