C#實(shí)現(xiàn)Post數(shù)據(jù)或文件到指定的服務(wù)器進(jìn)行接收
應(yīng)用場景
不同的接口服務(wù)器處理不同的應(yīng)用,我們會(huì)在實(shí)際應(yīng)用中將A服務(wù)器的數(shù)據(jù)提交給B服務(wù)器進(jìn)行數(shù)據(jù)接收并處理業(yè)務(wù)。
比如我們想要處理一個(gè)OFFICE文件,由用戶上傳到A服務(wù)器,上傳成功后,由B服務(wù)器負(fù)責(zé)進(jìn)行數(shù)據(jù)處理和下載工作,這時(shí)我們就需要 POST A服務(wù)器的文件數(shù)據(jù)到B服務(wù)器進(jìn)行處理。
實(shí)現(xiàn)原理
將用戶上傳的數(shù)據(jù)或A服務(wù)器已存在的數(shù)據(jù),通過form-data的形式POST到B服務(wù)器,B服務(wù)由指定ashx文件進(jìn)行數(shù)據(jù)接收,并轉(zhuǎn)由指定的業(yè)務(wù)邏輯程序進(jìn)行處理。如下圖:
實(shí)現(xiàn)代碼
PostAnyWhere類
創(chuàng)建一個(gè) PostAnyWhere 類,
該類具有如下屬性:
(1)public string PostUrl 要提交的服務(wù)器URL
(2)public List<PostFileItem> PostData 要準(zhǔn)備的數(shù)據(jù)(PostFileItem類可包括數(shù)據(jù)和文件類型)
該類包含的關(guān)鍵方法如下:
(1)public void AddText(string key, string value)
該方法將指定的字典數(shù)據(jù)加入到PostData中
(2)public void AddFile(string name, string srcFileName, string desName, string contentType = "text/plain")
該方法將指定的文件添加到PostData中,其中 srcFileName 表示要添加的文件名,desName表示接收數(shù)據(jù)生成的文件名
(3)public string Send()
該方法將開始POST傳送數(shù)據(jù)
代碼如下:
public class PostAnyWhere { public string PostUrl { get; set; } public List<PostFileItem> PostData { get; set; } public PostAnyWhere() { this.PostData = new List<PostFileItem>(); } public void AddText(string key, string value) { this.PostData.Add(new PostFileItem { Name = key, Value = value }); } public void AddFile(string name, string srcFileName, string desName,string at, string contentType = "text/plain") { string[] srcName = Path.GetFileName(srcFileName).Split('.'); string exName = ""; if (srcName.Length > 1) { exName = "."+srcName[srcName.Length-1]; } this.PostUrl = "https://www.xxx.com/test.ashx?guid=" + desName; ReadyFile(name, GetBinaryData(srcFileName), exName,contentType); } void ReadyFile(string name, byte[] fileBytes, string fileExName = "", string contentType = "text/plain") { this.PostData.Add(new PostFileItem { Type = PostFileItemType.File, Name = name, FileBytes = fileBytes, FileName = fileExName, ContentType = contentType }); } public string Send() { var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); var request = (HttpWebRequest)WebRequest.Create(this.PostUrl); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = "POST"; request.KeepAlive = true; Stream memStream = new System.IO.MemoryStream(); var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--"); var formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; var formFields = this.PostData.Where(m => m.Type == PostFileItemType.Text).ToList(); foreach (var d in formFields) { var textBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formdataTemplate, d.Name, d.Value)); memStream.Write(textBytes, 0, textBytes.Length); } const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; var files = this.PostData.Where(m => m.Type == PostFileItemType.File).ToList(); foreach (var fe in files) { memStream.Write(boundarybytes, 0, boundarybytes.Length); var header = string.Format(headerTemplate, fe.Name, fe.FileName ?? "System.Byte[]", fe.ContentType ?? "text/plain"); var headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); memStream.Write(fe.FileBytes, 0, fe.FileBytes.Length); } memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); request.ContentLength = memStream.Length; HttpWebResponse response; try { using (var requestStream = request.GetRequestStream()) { memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); } response = (HttpWebResponse)request.GetResponse(); } catch (WebException webException) { response = (HttpWebResponse)webException.Response; } if (response == null) { throw new Exception("HttpWebResponse is null"); } var responseStream = response.GetResponseStream(); if (responseStream == null) { throw new Exception("ResponseStream is null"); } using (var streamReader = new StreamReader(responseStream)) { return streamReader.ReadToEnd(); } } } public class PostFileItem { public PostFileItem() { this.Type = PostFileItemType.Text; } public PostFileItemType Type { get; set; } public string Value { get; set; } public byte[] FileBytes { get; set; } public string Name { get; set; } public string FileName { get; set; } public string ContentType { get; set; } } public enum PostFileItemType { Text = 0, File = 1 } public byte[] GetBinaryData(string filename) { if(!File.Exists(filename)) { return null; } try { FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); byte[] imageData = new Byte[fs.Length]; fs.Read( imageData, 0,Convert.ToInt32(fs.Length)); fs.Close(); return imageData; } catch(Exception) { return null; } finally { } }
ashx文件部署
在B服務(wù)器上部署ashx文件接收數(shù)據(jù),ashx程序即,一般處理程序(HttpHandler),一個(gè)httpHandler接受并處理一個(gè)http請(qǐng)求,需要實(shí)現(xiàn)IHttpHandler接口,這個(gè)接口有一個(gè)IsReusable成員,一個(gè)待實(shí)現(xiàn)的方法ProcessRequest(HttpContextctx) 。.ashx程序適合產(chǎn)生供瀏覽器處理的、不需要回發(fā)處理的數(shù)據(jù)格式。
示例代碼如下:
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.IO; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { if (context.Request.Files.Count > 0) { string strPath = System.Web.HttpContext.Current.Server.MapPath("~/app_data/test/"); string strName = context.Request.Files[0].FileName; string ext=Path.GetExtension(strName); string filename =HttpContext.Current.Request.QueryString["guid"].ToString()+Path.GetFileNameWithoutExtension(strName); if(ext!=""){ filename = filename + ext; } context.Request.Files[0].SaveAs(System.IO.Path.Combine(strPath, filename)); } } public bool IsReusable { get { return false; } } }
小結(jié)
ashx處理接收的數(shù)據(jù)后,后續(xù)還需要配合實(shí)際的接口功能繼續(xù)處理應(yīng)用。另外,對(duì)于ashx頁面,實(shí)際的應(yīng)用則需要使用安全訪問控制,只有正常登錄或提供合法訪問令牌的用戶才可以進(jìn)行訪問。
到此這篇關(guān)于C#實(shí)現(xiàn)Post數(shù)據(jù)或文件到指定的服務(wù)器進(jìn)行接收的文章就介紹到這了,更多相關(guān)C# Post數(shù)據(jù)或文件到指定服務(wù)器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
selenium.chrome寫擴(kuò)展攔截或轉(zhuǎn)發(fā)請(qǐng)求功能
Selenium?WebDriver?是一組開源?API,用于自動(dòng)測(cè)試?Web?應(yīng)用程序,利用它可以通過代碼來控制chrome瀏覽器,今天通過本文給大家介紹selenium?chrome寫擴(kuò)展攔截或轉(zhuǎn)發(fā)請(qǐng)求功能,感興趣的朋友一起看看吧2022-07-07