国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

HttpWebRequest的使用

2019-11-14 16:21:20
字體:
來源:轉載
供稿:網友

HttpWebRequest類主要利用HTTP 協議和服務器交互,通常是通過 GET 和 POST 兩種方式來對數據進行獲取和提交。下面對這兩種方式進行一下說明:

GET 方式

GET 方式通過在網絡地址附加參數來完成數據的提交,比如在地址 http://www.studyofnet.com/?hl=zh-CN 中,前面部分 http://www.studyofnet.com表示數據提交的網址,后面部分 hl=zh-CN 表示附加的參數,其中 hl 表示一個鍵(key), zh-CN 表示這個鍵對應的值(value)。

程序代碼如下:  

C# 代碼   復制
  HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.studyofnet.com?hl=zh-CN" );
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{//在這里對接收到的頁面內容進行處理}

使用 GET 方式提交中文數據。

GET 方式通過在網絡地址中附加參數來完成數據提交,對于中文的編碼,常用的有 gb2312 和 utf8 兩種。

用 gb2312 方式編碼訪問的程序代碼如下:

 
C# 代碼   復制
Encoding myEncoding = Encoding.GetEncoding("gb2312");
string address = "http://www.studyofnet.com/?" + HttpUtility.UrlEncode("參數一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{//在這里對接收到的頁面內容進行處理}

在上面的程序代碼中,我們以 GET 方式訪問了網址 http://www.studyofnet.com ,傳遞了參數“參數一=值一”,由于無法告知對方提交數據的編碼類型,所以編碼方式要以對方的網站為標準。

 

POST 方式

POST 方式通過在頁面內容中填寫參數的方法來完成數據的提交,參數的格式和 GET 方式一樣,是類似于 hl=zh-CN&newwindow=1 這樣的結構。

程序代碼如下:

 
C# 代碼   復制
string param = "hl=zh-CN&newwindow=1";
byte[] bs = Encoding.ASCII.GetBytes(param);
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.studyofnet.com/" );
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{   reqStream.Write(bs, 0, bs.Length);}using (WebResponse wr = req.GetResponse()){   //在這里對接收到的頁面內容進行處理}  

在上面的代碼中,我們訪問了 http://www.studyofnet.com 的網址,分別以 GET 和 POST 方式提交了數據,并接收了返回的頁面內容。然而,如果提交的參數中含有中文,那么這樣的處理是不夠的,需要對其進行編碼,讓對方網站能夠識別。  

使用 POST 方式提交中文數據

POST 方式通過在頁面內容中填寫參數的方法來完成數據的提交,由于提交的參數中可以說明使用的編碼方式,所以理論上能獲得更大的兼容性。

用 gb2312 方式編碼訪問的程序代碼如下:  

C# 代碼   復制
 Encoding myEncoding = Encoding.GetEncoding("gb2312");
string param = HttpUtility.UrlEncode("參數一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding) + "&" + HttpUtility.UrlEncode("參數二", myEncoding) + "=" + HttpUtility.UrlEncode("值二", myEncoding);
byte[] postBytes = Encoding.ASCII.GetBytes(param);
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.studyofnet.com/" );
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
req.ContentLength = postBytes.Length;
using (Stream reqStream = req.GetRequestStream())
{   reqStream.Write(bs, 0, bs.Length);}using (WebResponse wr = req.GetResponse()){   //在這里對接收到的頁面內容進行處理} 

從上面的代碼可以看出, POST 中文數據的時候,先使用 UrlEncode 方法將中文字符轉換為編碼后的 ASCII 碼,然后提交到服務器,提交的時候可以說明編碼的方式,用來使對方服務器能夠正確的解析。  

用C#語言寫的關于HttpWebRequest 類的使用方法

 
C# 代碼   復制
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace HttpWeb
{    /// <summary>     ///  Http操作類     /// </summary>     public static class httptest    {        /// <summary>         ///  獲取網址HTML         /// </summary>         /// <param name="URL">網址 </param>         /// <returns> </returns>         public static string GetHtml(string URL)        {            WebRequest wrt;            wrt = WebRequest.Create(URL);            wrt.Credentials = CredentialCache.DefaultCredentials;            WebResponse wrp;            wrp = wrt.GetResponse();            string reader = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();            try            {                wrt.GetResponse().Close();            }            catch (WebException ex)            {                throw ex;            }            return reader;        }        /// <summary>         /// 獲取網站cookie         /// </summary>         /// <param name="URL">網址 </param>         /// <param name="cookie">cookie </param>         /// <returns> </returns>         public static string GetHtml(string URL, out string cookie)        {            WebRequest wrt;            wrt = WebRequest.Create(URL);            wrt.Credentials = CredentialCache.DefaultCredentials;            WebResponse wrp;            wrp = wrt.GetResponse();            string html = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();            try            {                wrt.GetResponse().Close();            }            catch (WebException ex)            {                throw ex;            }            cookie = wrp.Headers.Get("Set-Cookie");            return html;        }        public static string GetHtml(string URL, string postData, string cookie, out string header, string server)        {            return GetHtml(server, URL, postData, cookie, out header);        }        public static string GetHtml(string server, string URL, string postData, string cookie, out string header)        {            byte[] byteRequest = Encoding.GetEncoding("gb2312").GetBytes(postData);            return GetHtml(server, URL, byteRequest, cookie, out header);        }        public static string GetHtml(string server, string URL, byte[] byteRequest, string cookie, out string header)        {            byte[] bytes = GetHtmlByBytes(server, URL, byteRequest, cookie, out header);            Stream getStream = new MemoryStream(bytes);            StreamReader streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));            string getString = streamReader.ReadToEnd();            streamReader.Close();            getStream.Close();            return getString;        }        /// <summary>         /// Post模式瀏覽         /// </summary>         /// <param name="server">服務器地址 </param>         /// <param name="URL">網址 </param>         /// <param name="byteRequest">流 </param>         /// <param name="cookie">cookie </param>         /// <param name="header">句柄 </param>         /// <returns> </returns>         public static byte[] GetHtmlByBytes(string server, string URL, byte[] byteRequest, string cookie, out string header)        {            long contentLength;            HttpWebRequest httpWebRequest;            HttpWebResponse webResponse;            Stream getStream;            httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);            CookieContainer co = new CookieContainer();            co.SetCookies(new Uri(server), cookie);            httpWebRequest.CookieContainer = co;            httpWebRequest.ContentType = "application/x-www-form-urlencoded";            httpWebRequest.Accept =                "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-Flash, application/vnd.ms-Excel, application/vnd.ms-Powerpoint, application/msWord, */*";            httpWebRequest.Referer = server;            httpWebRequest.UserAgent =                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";            httpWebRequest.Method = "Post";            httpWebRequest.ContentLength = byteRequest.Length;            Stream stream;            stream = httpWebRequest.GetRequestStream();            stream.Write(byteRequest, 0, byteRequest.Length);            stream.Close();            webResponse = (HttpWebResponse)httpWebRequest.GetResponse();            header = webResponse.Headers.ToString();            getStream = webResponse.GetResponseStream();            contentLength = webResponse.ContentLength;            byte[] outBytes = new byte[contentLength];            outBytes = ReadFully(getStream);            getStream.Close();            return outBytes;        }        public static byte[] ReadFully(Stream stream)        {            byte[] buffer = new byte[128];            using (MemoryStream ms = new MemoryStream())            {                while (true)                {                    int read = stream.Read(buffer, 0, buffer.Length);                    if (read <= 0)                        return ms.ToArray();                    ms.Write(buffer, 0, read);                }            }        }        /// <summary>         /// Get模式         /// </summary>         /// <param name="URL">網址 </param>         /// <param name="cookie">cookies </param>         /// <param name="header">句柄 </param>         /// <param name="server">服務器 </param>         /// <param name="val">服務器 </param>         /// <returns> </returns>         public static string GetHtml(string URL, string cookie, out string header, string server)        {            return GetHtml(URL, cookie, out header, server, "");        }        /// <summary>         /// Get模式瀏覽         /// </summary>         /// <param name="URL">Get網址 </param>         /// <param name="cookie">cookie </param>         /// <param name="header">句柄 </param>         /// <param name="server">服務器地址 </param>         /// <param name="val"> </param>         /// <returns> </returns>         public static string GetHtml(string URL, string cookie, out string header, string server, string val)        {            HttpWebRequest httpWebRequest;            HttpWebResponse webResponse;            Stream getStream;            StreamReader streamReader;            string getString = "";            httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);            httpWebRequest.Accept = "*/*";            httpWebRequest.Referer = server;            CookieContainer co = new CookieContainer();            co.SetCookies(new Uri(server), cookie);            httpWebRequest.CookieContainer = co;            httpWebRequest.UserAgent =                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";            httpWebRequest.Method = "GET";            webResponse = (HttpWebResponse)httpWebRequest.GetResponse();            header = webResponse.Headers.ToString();            getStream = webResponse.GetResponseStream();            streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));            getString = streamReader.ReadToEnd();            streamReader.Close();            getStream.Close();            return getString;        }   }}

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 延津县| 米脂县| 肃北| 石河子市| 湖北省| 搜索| 敦化市| 嘉鱼县| 莱芜市| 成安县| 临城县| 曲阳县| 天镇县| 彭阳县| 读书| 邹城市| 泾阳县| 柯坪县| 安庆市| 尚义县| 高密市| 晋宁县| 辽阳市| 庄浪县| 景东| 桃园市| 九台市| 武夷山市| 邯郸县| 六安市| 望城县| 阳谷县| 孟津县| 德兴市| 中宁县| 瑞金市| 儋州市| 宁强县| 库伦旗| 鄱阳县| 崇义县|