1. 程式人生 > >C#中HttpWebRequest的用法詳解

C#中HttpWebRequest的用法詳解

網站 default 編碼方式 對數 c# toarray collect acc like

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

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

GET 方式:

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

程序代碼如下:


代碼如下:

HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( “http://www.jb51.net?hl=zh-CN” );

req.Method = “GET”;

using (WebResponse wr = req.GetResponse())

{

//在這裏對接收到的頁面內容進行處理

}

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

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

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


代碼如下:

Encoding myEncoding = Encoding.GetEncoding(“gb2312”);

string address = “http://www.jb51.net/?” + HttpUtility.UrlEncode(“參數一”, myEncoding) + “=” + HttpUtility.UrlEncode(“值一”, myEncoding);

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);

req.Method = “GET”;

using (WebResponse wr = req.GetResponse())

{

//在這裏對接收到的頁面內容進行處理

}

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

POST 方式:

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

程序代碼如下:


代碼如下:

string param = “hl=zh-CN&newwindow;=1”;

byte[] bs = Encoding.ASCII.GetBytes(param);

HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( “http://www.jb51.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())

{

//在這裏對接收到的頁面內容進行處理

}

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

使用 POST 方式提交中文數據

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

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


代碼如下:

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.jb51.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())

{

//在這裏對接收到的頁面內容進行處理

}

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

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


代碼如下:

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;

}

}

}

除聲明外,跑步客文章均為原創,轉載請以鏈接形式標明本文地址
C#中HttpWebRequest的用法詳解

本文地址: http://www.paobuke.com/develop/c-develop/pbk23338.html






相關內容

技術分享圖片C#實現文件壓縮與解壓的方法示例【ZIP格式】技術分享圖片Winform窗體傳值的方法(示例)技術分享圖片C#簡單寫入xml文件的方法技術分享圖片C#利用控件拖拽技術制作拼圖遊戲
技術分享圖片C#實現將日誌寫入文本文件的方法技術分享圖片C#創建、讀取和修改Excel的方法技術分享圖片.NETà?????ê??÷(GC)?-àí?3??技術分享圖片C#定時關閉窗體實例

C#中HttpWebRequest的用法詳解