C#中HttpWebRequest的用法詳解
本文實(shí)例講述了C#中HttpWebRequest的用法。分享給大家供大家參考。具體如下:
HttpWebRequest類主要利用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.dhdzp.com/?hl=zh-CN 中,前面部分 http://www.dhdzp.com表示數(shù)據(jù)提交的網(wǎng)址,后面部分 hl=zh-CN 表示附加的參數(shù),其中 hl 表示一個(gè)鍵(key), zh-CN 表示這個(gè)鍵對(duì)應(yīng)的值(value)。
程序代碼如下:
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)的程序代碼如下:
string address = "http://www.dhdzp.com/?" + 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.dhdzp.com ,傳遞了參數(shù)“參數(shù)一=值一”,由于無(wú)法告知對(duì)方提交數(shù)據(jù)的編碼類型,所以編碼方式要以對(duì)方的網(wǎng)站為標(biāo)準(zhǔn)。
POST 方式:
POST 方式通過(guò)在頁(yè)面內(nèi)容中填寫參數(shù)的方法來(lái)完成數(shù)據(jù)的提交,參數(shù)的格式和 GET 方式一樣,是類似于 hl=zh-CN&newwindow=1 這樣的結(jié)構(gòu)。
程序代碼如下:
byte[] bs = Encoding.ASCII.GetBytes(param);
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.dhdzp.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())
{
//在這里對(duì)接收到的頁(yè)面內(nèi)容進(jìn)行處理
}
在上面的代碼中,我們?cè)L問(wèn)了 http://www.dhdzp.com 的網(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)容中填寫參數(shù)的方法來(lái)完成數(shù)據(jù)的提交,由于提交的參數(shù)中可以說(shuō)明使用的編碼方式,所以理論上能獲得更大的兼容性。
用 gb2312 方式編碼訪問(wèn)的程序代碼如下:
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.dhdzp.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())
{
//在這里對(duì)接收到的頁(yè)面內(nèi)容進(jìn)行處理
}
從上面的代碼可以看出, POST 中文數(shù)據(jù)的時(shí)候,先使用 UrlEncode 方法將中文字符轉(zhuǎn)換為編碼后的 ASCII 碼,然后提交到服務(wù)器,提交的時(shí)候可以說(shuō)明編碼的方式,用來(lái)使對(duì)方服務(wù)器能夠正確的解析。
用C#語(yǔ)言寫的關(guān)于HttpWebRequest 類的使用方法
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace HttpWeb
{
/// <summary>
/// Http操作類
/// </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)文章
C#使用動(dòng)態(tài)規(guī)劃解決0-1背包問(wèn)題實(shí)例分析
這篇文章主要介紹了C#使用動(dòng)態(tài)規(guī)劃解決0-1背包問(wèn)題,實(shí)例分析了C#動(dòng)態(tài)規(guī)劃算法的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-04-04
C#實(shí)現(xiàn)將浮點(diǎn)數(shù)表示的貨幣數(shù)量以漢字大寫形式輸出的方法
這篇文章主要介紹了C#實(shí)現(xiàn)將浮點(diǎn)數(shù)表示的貨幣數(shù)量以漢字大寫形式輸出的方法,涉及C#針對(duì)浮點(diǎn)數(shù)的遍歷與字符替換操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08
Win10下C# DateTime出現(xiàn)星期幾問(wèn)題的解決方法
這篇文章主要介紹了Win10下C# DateTime出現(xiàn)星期幾問(wèn)題的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-10-10
C# 打印網(wǎng)頁(yè)不顯示頁(yè)眉頁(yè)腳的實(shí)現(xiàn)方法
這篇文章主要介紹了C# 打印網(wǎng)頁(yè)不顯示頁(yè)眉頁(yè)腳的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
C# 控制臺(tái)實(shí)現(xiàn)一次性輸入多行的操作
這篇文章主要介紹了C# 控制臺(tái)實(shí)現(xiàn)一次性輸入多行的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01
Unity shader實(shí)現(xiàn)移動(dòng)端模擬深度水效果
這篇文章主要為大家詳細(xì)介紹了Unity shader實(shí)現(xiàn)移動(dòng)端模擬深度水效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05

