一 簡介
HttpWebRequest和HttpWebResponse類是用於發送和接收HTTP數據的最好選擇。它們支持一系列有用的屬性。這兩個類位 於System.Net命名空間,默認情況下這個類對於控制台程序來說是可訪問的。請注意,HttpWebRequest對象不是利用new關鍵字通過構 造函數來創建的,而是利用工廠機制(factory mechanism)通過Create()方法來創建的。另外,你可能預計需要顯式地調用一個“Send”方法,實際上不需要。接下來調用 HttpWebRequest.GetResponse()方法返回的是一個HttpWebResponse對象。你可以把HTTP響應的數據流 (stream)綁定到一個StreamReader對象,然后就可以通過ReadToEnd()方法把整個HTTP響應作為一個字符串取回。也可以通過 StreamReader.ReadLine()方法逐行取回HTTP響應的內容。
二 場景
就像上面所說的那樣這兩個對象的傳輸都是以流的方式在網絡中傳輸的,如果我想要從客戶端向服務器發送一個實體對象的數據該怎么解決呢?可能有的人說使用wcf等通信技術,但是對於我的應用場景來說有點小題大做,於是在網上找了點資料,實現了基於HttpWebReques的數據對象的傳輸。
三 具體實現
首先,創建需要傳輸的實體類PostParameters,這個實體類中有兩個屬性,一個是要傳輸的文件的文件流,另一個是文件路徑(當然,因為我的需求是要上傳圖片的,沒有做過多的擴展,后綴名,文件格式等的需求,可以根據自己的需求去做擴展)
public class PostParameters { // public string Name { get; set; } public Stream FStream { get; set; } public string Path { get; set; } }
下面是客戶端的代碼,利用HttpWebRequest傳輸實體對象數據
using System; using System.IO; using System.Linq; using System.Net; using System.Text; using Newtonsoft.Json; namespace AshxRequestTest { internal class Program { private static void Main(string[] args) { PostJson("http://uploadimg.zhtx.com/UploadImagHandle.ashx", new PostParameters { Path = "hahah" }); } private static void PostJson(string uri, PostParameters postParameters) { string postData = JsonConvert.SerializeObject(postParameters); //將對象序列化 byte[] bytes = Encoding.UTF8.GetBytes(postData); //轉化為數據流 var httpWebRequest = (HttpWebRequest) WebRequest.Create(uri); //創建HttpWebRequest對象 httpWebRequest.Method = "POST"; httpWebRequest.ContentLength = bytes.Length; httpWebRequest.ContentType = "text/xml"; using (Stream requestStream = httpWebRequest.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Count()); //輸出流中寫入數據 } var httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse(); //創建響應對象 if (httpWebResponse.StatusCode != HttpStatusCode.OK) //判斷響應狀態碼 { string message = String.Format("POST failed. Received HTTP {0}", httpWebResponse.StatusCode); throw new ApplicationException(message); } } } }
注釋寫的很清楚,
下面是服務端的代碼:
using System; using System.IO; using System.Text; using System.Web; using Newtonsoft.Json; namespace HttpWebClientTest { /// <summary> /// UploadImagHandle 的摘要說明 /// create by peng.li 2015-5-30 /// </summary> public class UploadImagHandle : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/xml"; HandleMethod(); // context.Response.Write("Hello World"); } public bool IsReusable { get { return false; } } private static void HandleMethod() { HttpContext httpContext = HttpContext.Current; Stream httpRStream = httpContext.Request.InputStream; var bytes = new byte[httpRStream.Length]; httpRStream.Read(bytes, 0, bytes.Length); //讀取請求流對象 string req = Encoding.Default.GetString(bytes); //轉換成字符串對象(這個字符串是json格式的) var postParameters = JsonConvert.DeserializeObject<PostParameters>(req); //(反序列化) int res = UploadImage(postParameters); httpContext.Response.Write(res); } public static int UploadImage(PostParameters postParameters) { string path = "E:/" + postParameters.Path; try { if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } File.WriteAllBytes(path, postParameters.FileByte); return 1; } catch (Exception) { return 0; } } } }
這只是一個小的demo,希望能夠起到拋磚引玉的作用,當然有表達錯誤的地方,也希望大家能指出來,一塊學習,一塊進步。
本人的.NET學習技術交流群:226704167
另附上demo下載鏈接:http://files.cnblogs.com/files/lip0121/HttpWebClientTestPostJson.rar