最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#中HttpWebRequest的用法詳解

 更新時(shí)間:2014年11月06日 11:00:53   投稿:shichen2014  
這篇文章主要介紹了C#中HttpWebRequest的用法,以實(shí)例的形式詳細(xì)敘述了HttpWebRequest類(lèi)中GET與POST的用法,非常具有參考借鑒價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了C#中HttpWebRequest的用法。分享給大家供大家參考。具體如下:

HttpWebRequest類(lèi)主要利用HTTP 協(xié)議和服務(wù)器交互,通常是通過(guò) GET 和 POST 兩種方式來(lái)對(duì)數(shù)據(jù)進(jìn)行獲取和提交。下面對(duì)這兩種方式進(jìn)行一下說(shuō)明:

GET 方式:
GET 方式通過(guò)在網(wǎng)絡(luò)地址附加參數(shù)來(lái)完成數(shù)據(jù)的提交,比如在地址 http://www.fzitv.net/?hl=zh-CN 中,前面部分 http://www.fzitv.net表示數(shù)據(jù)提交的網(wǎng)址,后面部分 hl=zh-CN 表示附加的參數(shù),其中 hl 表示一個(gè)鍵(key), zh-CN 表示這個(gè)鍵對(duì)應(yīng)的值(value)。
程序代碼如下: 

復(fù)制代碼 代碼如下:
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.fzitv.net?hl=zh-CN" );
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在這里對(duì)接收到的頁(yè)面內(nèi)容進(jìn)行處理
}

使用 GET 方式提交中文數(shù)據(jù)。

GET 方式通過(guò)在網(wǎng)絡(luò)地址中附加參數(shù)來(lái)完成數(shù)據(jù)提交,對(duì)于中文的編碼,常用的有 gb2312 和 utf8 兩種。
用 gb2312 方式編碼訪問(wèn)的程序代碼如下:

復(fù)制代碼 代碼如下:
Encoding myEncoding = Encoding.GetEncoding("gb2312");
string address = "http://www.fzitv.net/?" + HttpUtility.UrlEncode("參數(shù)一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在這里對(duì)接收到的頁(yè)面內(nèi)容進(jìn)行處理
}

在上面的程序代碼中,我們以 GET 方式訪問(wèn)了網(wǎng)址 http://www.fzitv.net ,傳遞了參數(shù)“參數(shù)一=值一”,由于無(wú)法告知對(duì)方提交數(shù)據(jù)的編碼類(lèi)型,所以編碼方式要以對(duì)方的網(wǎng)站為標(biāo)準(zhǔn)。
 
POST 方式:

POST 方式通過(guò)在頁(yè)面內(nèi)容中填寫(xiě)參數(shù)的方法來(lái)完成數(shù)據(jù)的提交,參數(shù)的格式和 GET 方式一樣,是類(lèi)似于 hl=zh-CN&newwindow=1 這樣的結(jié)構(gòu)。
程序代碼如下:

復(fù)制代碼 代碼如下:
string param = "hl=zh-CN&newwindow=1";
byte[] bs = Encoding.ASCII.GetBytes(param);
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.fzitv.net/" );
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())
{
   //在這里對(duì)接收到的頁(yè)面內(nèi)容進(jìn)行處理
}

在上面的代碼中,我們?cè)L問(wèn)了 http://www.fzitv.net 的網(wǎng)址,分別以 GET 和 POST 方式提交了數(shù)據(jù),并接收了返回的頁(yè)面內(nèi)容。然而,如果提交的參數(shù)中含有中文,那么這樣的處理是不夠的,需要對(duì)其進(jìn)行編碼,讓對(duì)方網(wǎng)站能夠識(shí)別。 
使用 POST 方式提交中文數(shù)據(jù)
POST 方式通過(guò)在頁(yè)面內(nèi)容中填寫(xiě)參數(shù)的方法來(lái)完成數(shù)據(jù)的提交,由于提交的參數(shù)中可以說(shuō)明使用的編碼方式,所以理論上能獲得更大的兼容性。
用 gb2312 方式編碼訪問(wèn)的程序代碼如下: 

復(fù)制代碼 代碼如下:
Encoding myEncoding = Encoding.GetEncoding("gb2312");
string param = HttpUtility.UrlEncode("參數(shù)一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding) + "&" + HttpUtility.UrlEncode("參數(shù)二", myEncoding) + "=" + HttpUtility.UrlEncode("值二", myEncoding);
byte[] postBytes = Encoding.ASCII.GetBytes(param);
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.fzitv.net/" );
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())
{
   //在這里對(duì)接收到的頁(yè)面內(nèi)容進(jìn)行處理
}

從上面的代碼可以看出, POST 中文數(shù)據(jù)的時(shí)候,先使用 UrlEncode 方法將中文字符轉(zhuǎn)換為編碼后的 ASCII 碼,然后提交到服務(wù)器,提交的時(shí)候可以說(shuō)明編碼的方式,用來(lái)使對(duì)方服務(wù)器能夠正確的解析。 
用C#語(yǔ)言寫(xiě)的關(guān)于HttpWebRequest 類(lèi)的使用方法
復(fù)制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace HttpWeb
{
    /// <summary>
    ///  Http操作類(lèi)
    /// </summary>
    public static class httptest
    {
        /// <summary>
        ///  獲取網(wǎng)址HTML
        /// </summary>
        /// <param name="URL">網(wǎng)址 </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>
        /// 獲取網(wǎng)站cookie
        /// </summary>
        /// <param name="URL">網(wǎng)址 </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">服務(wù)器地址 </param>
        /// <param name="URL">網(wǎng)址 </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">網(wǎng)址 </param>
        /// <param name="cookie">cookies </param>
        /// <param name="header">句柄 </param>
        /// <param name="server">服務(wù)器 </param>
        /// <param name="val">服務(wù)器 </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網(wǎng)址 </param>
        /// <param name="cookie">cookie </param>
        /// <param name="header">句柄 </param>
        /// <param name="server">服務(wù)器地址 </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;
        }
   }
}

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論

开鲁县| 德令哈市| 读书| 德格县| 乌拉特后旗| 丰都县| 阿克陶县| 海安县| 颍上县| 扶沟县| 石狮市| 高密市| 花垣县| 襄城县| 高州市| 商河县| 开化县| 依安县| 横山县| 高陵县| 通海县| 阿合奇县| 佛山市| 兰溪市| 马公市| 边坝县| 嘉义县| 阿坝县| 来宾市| 宁武县| 林周县| 竹山县| 怀仁县| 英山县| 赤城县| 泸溪县| 永胜县| 水城县| 固安县| 南通市| 昭平县|