C#中HttpWebRequest的用法詳解
本文實例講述了C#中HttpWebRequest的用法。分享給大家供大家參考。具體如下:
HttpWebRequest類主要利用HTTP 協(xié)議和服務器交互,通常是通過 GET 和 POST 兩種方式來對數(shù)據(jù)進行獲取和提交。下面對這兩種方式進行一下說明:
GET 方式:
GET 方式通過在網(wǎng)絡地址附加參數(shù)來完成數(shù)據(jù)的提交,比如在地址 http://www.dbjr.com.cn/?hl=zh-CN 中,前面部分 http://www.dbjr.com.cn表示數(shù)據(jù)提交的網(wǎng)址,后面部分 hl=zh-CN 表示附加的參數(shù),其中 hl 表示一個鍵(key), zh-CN 表示這個鍵對應的值(value)。
程序代碼如下:
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在這里對接收到的頁面內容進行處理
}
使用 GET 方式提交中文數(shù)據(jù)。
GET 方式通過在網(wǎng)絡地址中附加參數(shù)來完成數(shù)據(jù)提交,對于中文的編碼,常用的有 gb2312 和 utf8 兩種。
用 gb2312 方式編碼訪問的程序代碼如下:
string address = "http://www.dbjr.com.cn/?" + HttpUtility.UrlEncode("參數(shù)一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在這里對接收到的頁面內容進行處理
}
在上面的程序代碼中,我們以 GET 方式訪問了網(wǎng)址 http://www.dbjr.com.cn ,傳遞了參數(shù)“參數(shù)一=值一”,由于無法告知對方提交數(shù)據(jù)的編碼類型,所以編碼方式要以對方的網(wǎng)站為標準。
POST 方式:
POST 方式通過在頁面內容中填寫參數(shù)的方法來完成數(shù)據(jù)的提交,參數(shù)的格式和 GET 方式一樣,是類似于 hl=zh-CN&newwindow=1 這樣的結構。
程序代碼如下:
byte[] bs = Encoding.ASCII.GetBytes(param);
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.dbjr.com.cn/" );
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.dbjr.com.cn 的網(wǎng)址,分別以 GET 和 POST 方式提交了數(shù)據(jù),并接收了返回的頁面內容。然而,如果提交的參數(shù)中含有中文,那么這樣的處理是不夠的,需要對其進行編碼,讓對方網(wǎng)站能夠識別。
使用 POST 方式提交中文數(shù)據(jù)
POST 方式通過在頁面內容中填寫參數(shù)的方法來完成數(shù)據(jù)的提交,由于提交的參數(shù)中可以說明使用的編碼方式,所以理論上能獲得更大的兼容性。
用 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.dbjr.com.cn/" );
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 中文數(shù)據(jù)的時候,先使用 UrlEncode 方法將中文字符轉換為編碼后的 ASCII 碼,然后提交到服務器,提交的時候可以說明編碼的方式,用來使對方服務器能夠正確的解析。
用C#語言寫的關于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">服務器地址 </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">服務器 </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網(wǎng)址 </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#程序設計有所幫助。
相關文章
C#中Parallel類For、ForEach和Invoke使用介紹
這篇文章介紹了C#中Parallel類For、ForEach和Invoke的使用方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04C# menuStrip控件實現(xiàn)鼠標滑過自動彈出功能
MenuStrip 控件是 Visual Studio 和 .NET Framework 中的功能。使用該控件,可以輕松創(chuàng)建 Microsoft Office 中那樣的菜單。本文給大家分享menuStrip鼠標滑過自動彈出效果2021-07-07C#環(huán)形緩沖區(qū)(隊列)完全實現(xiàn)
這篇文章主要為大家詳細介紹了C#環(huán)形緩沖區(qū)(隊列)完全實現(xiàn)代碼,感興趣的小伙伴們可以參考一下2016-07-07C#創(chuàng)建、部署、調用WebService圖文實例詳解
本文主要用詳細的圖文給大家介紹C#創(chuàng)建、部署、調用WebService的全部過程以及中間需要避免的問題。2017-11-11c#中WinForm用OpencvSharp實現(xiàn)ROI區(qū)域提取的示例
已經(jīng)自學OpencvSharp一段時間了,現(xiàn)在就分享一下我的學習過程,本文主要介紹了c#中WinForm用OpencvSharp實現(xiàn)ROI區(qū)域提取的示例,具有一定的參考價值,感興趣的可以了解一下2022-05-05C#獲取DataTable對象狀態(tài)DataRowState
這篇文章介紹了C#獲取DataTable對象狀態(tài)DataRowState的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02