HttpWebRequest WebResponse 对象简单了解
1.HTTP亦即Hpyer Text Transfer Protocal的縮寫,它是現代互聯網上最重要的一種網絡協議,超文本傳輸協議位于TCP/IP協議的應用層,是一個面向?? 無連接、簡單、快速的C/S結構的協議 。HTTP的工作過程大體上分連接、請求、響應和斷開連接
2..NET類庫中提供了WebRequest和WebResponse就是利用這兩個類實現的網絡功能
?HttpWebRequest:HttpWebRequest 類對 WebRequest 中定義的屬性和方法提供支持,也對使用戶能夠直接與使用
?????????????????????????? HTTP 的服務器交互的附加 屬性和方法提供支持。
?????????????????????????? http://msdn.microsoft.com/zh-cn/library/system.net.httpwebrequest.connection(v=VS.80).aspx
WebResponse 類是 abstract 基類,協議特定的響應類從該抽象基類派生。應用程序可以使用 WebResponse 類的實例以協議不可知的方式參與請求和響應事務,而從 WebResponse 派生的協議特定的類攜帶請求的詳細信息
?????????????????????????? http://msdn.microsoft.com/zh-cn/library/system.net.webresponse(v=VS.80).aspx
3.簡單應用:
???? 導入命名空間:using System.Net?? using System.IO?
??? 程序使用 HTTP 協議和服務器交互主要是進行數據的提交,通常數據的提交是通過 GET 和 POST 兩種方式
????//創建一個url新的httpwebrequest 對象?
??? HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:1782/WebForm1.aspx?");
?? //設置myHttpWebRequest 對象屬性
?? ?myHttpWebRequest.Method = "post"
? ? myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
?? myHttpWebRequest.UserAgent = ".NET Framework Client";
??? //輸入參數 id=中文和Econding
????string inputData = System.Console.ReadLine();?
?? //創建utf-8?或者GB2312 來處理中文?
?? // 處理英文就是這個就可以
? //ASCIIEncoding encoding = new ASCIIEncoding();
? ?Encoding myEncoding = Encoding.GetEncoding("utf-8");
? byte[] byteinputdata = myEncoding.GetBytes(inputData);
? //寫入當前流對象發送個服務器
? myHttpWebRequest.ContentLength = byteinputdata.Length;
? Stream newStream = myHttpWebRequest.GetRequestStream();
? newStream.Write(byteinputdata, 0, byteinputdata.Length); ?
??newStream.Close();
?
?//獲取服務器響應的結果(根據條件獲取對象解析返回結果)
?? ?HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
??? Stream streamResponse = myHttpWebResponse.GetResponseStream(); ?
??? StreamReader streamRead = new StreamReader(streamResponse);???????
??? Char[] readBuff = new Char[256]; ?
??? int count = streamRead.Read(readBuff, 0, 256);
????System.Console.WriteLine("\nThe contents of HTML Page are :\n"); ???
?????while (count > 0) ???????????
??? { ??????????????
????? String outputData = new String(readBuff, 0, count); ??
???? ?System.Console.Write(outputData); ?????????????
???? ?count = streamRead.Read(readBuff, 0, 256); ?????
?????}????????????
??? streamRead.Close(); ?????????
??? streamResponse.Close();
?? myHttpWebResponse.Close();
?
?
?
?
轉載于:https://www.cnblogs.com/linsu/archive/2011/12/04/2276124.html
總結
以上是生活随笔為你收集整理的HttpWebRequest WebResponse 对象简单了解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: freetextbox文本编辑器
- 下一篇: 【转】OpenCV里IplImage数据