欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C#教程

當(dāng)前位置:主頁 > 軟件編程 > C#教程 >

淺談C#中HttpWebRequest與HttpWebResponse的使用方法

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C#教程|點(diǎn)擊: 次

這個(gè)類是專門為HTTP的GET和POST請求寫的,解決了編碼,證書,自動(dòng)帶Cookie等問題。

C# HttpHelper,幫助類,真正的Httprequest請求時(shí)無視編碼,無視證書,無視Cookie,網(wǎng)頁抓取

1.第一招,根據(jù)URL地址獲取網(wǎng)頁信息

先來看一下代碼

get方法

public static string GetUrltoHtml(string Url,string type)
{
 try
 {
  System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
  // Get the response instance.
  System.Net.WebResponse wResp = wReq.GetResponse();
  System.IO.Stream respStream = wResp.GetResponseStream();
  // Dim reader As StreamReader = New StreamReader(respStream)
  using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
  {
   return reader.ReadToEnd();
  }
 }
 catch (System.Exception ex)
 {
  //errorMsg = ex.Message;
 }
 return "";
}

post方法

///<summary>
///采用https協(xié)議訪問網(wǎng)絡(luò)
///</summary>
public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding)
{
 Encoding encoding = Encoding.Default;
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
 request.Method = "post";
 request.Accept = "text/html, application/xhtml+xml, */*";
 request.ContentType = "application/x-www-form-urlencoded";
 byte[] buffer = encoding.GetBytes(strPostdata);
 request.ContentLength = buffer.Length;
 request.GetRequestStream().Write(buffer, 0, buffer.Length);
 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 using( StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))
  {
   return reader.ReadToEnd();
  }
}

這招是入門第一式, 特點(diǎn):

1.最簡單最直觀的一種,入門課程。

2.適應(yīng)于明文,無需登錄,無需任何驗(yàn)證就可以進(jìn)入的頁面。

3.獲取的數(shù)據(jù)類型為HTML文檔。

4.請求方法為Get/Post

2.第二招,根據(jù)URL地址獲取需要驗(yàn)證證書才能訪問的網(wǎng)頁信息

先來看一下代碼

get方法

 //回調(diào)驗(yàn)證證書問題
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{ 
 // 總是接受 
 return true;
}
/// <summary>
/// 傳入U(xiǎn)RL返回網(wǎng)頁的html代碼
/// </summary>
public string GetUrltoHtml(string Url)
{
 StringBuilder content = new StringBuilder();
 try
 {
  //這一句一定要寫在創(chuàng)建連接的前面。使用回調(diào)的方法進(jìn)行證書驗(yàn)證。
  ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
  // 與指定URL創(chuàng)建HTTP請求
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  //創(chuàng)建證書文件
  X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer");
  //添加到請求里
  request.ClientCertificates.Add(objx509);
  // 獲取對應(yīng)HTTP請求的響應(yīng)
  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  // 獲取響應(yīng)流
  Stream responseStream = response.GetResponseStream();
  // 對接響應(yīng)流(以"GBK"字符集)
  StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
  // 開始讀取數(shù)據(jù)
  Char[] sReaderBuffer = new Char[256];
  int count = sReader.Read(sReaderBuffer, 0, 256);
  while (count > 0)
  {
   String tempStr = new String(sReaderBuffer, 0, count);
   content.Append(tempStr);
   count = sReader.Read(sReaderBuffer, 0, 256);
  }
  // 讀取結(jié)束
  sReader.Close();
 }
 catch (Exception)
 {
  content = new StringBuilder("Runtime Error");
 }
 return content.ToString();
}

post方法

//回調(diào)驗(yàn)證證書問題
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
 // 總是接受 
 return true;
}
///<summary>
///采用https協(xié)議訪問網(wǎng)絡(luò)
///</summary>
public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding)
{
 // 這一句一定要寫在創(chuàng)建連接的前面。使用回調(diào)的方法進(jìn)行證書驗(yàn)證。
 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
 Encoding encoding = Encoding.Default;
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
 //創(chuàng)建證書文件
 X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer");
 //加載Cookie
 request.CookieContainer = new CookieContainer();
 //添加到請求里
 request.ClientCertificates.Add(objx509);
 request.Method = "post";
 request.Accept = "text/html, application/xhtml+xml, */*";
 request.ContentType = "application/x-www-form-urlencoded";
 byte[] buffer = encoding.GetBytes(strPostdata);
 request.ContentLength = buffer.Length;
 request.GetRequestStream().Write(buffer, 0, buffer.Length);
 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))
  {
   return reader.ReadToEnd();
  }
}

這招是學(xué)會(huì)算是進(jìn)了大門了,凡是需要驗(yàn)證證書才能進(jìn)入的頁面都可以使用這個(gè)方法進(jìn)入,我使用的是證書回調(diào)驗(yàn)證的方式,證書驗(yàn)證是否通過在客戶端驗(yàn)證,這樣的話我們就可以使用自己定義一個(gè)方法來驗(yàn)證了,有的人會(huì)說那也不清楚是怎么樣驗(yàn)證的啊,其它很簡單,代碼是自己寫的為什么要那么難為自己呢,直接返回一個(gè)True不就完了,永遠(yuǎn)都是驗(yàn)證通過,這樣就可以無視證書的存在了, 特點(diǎn):

1.入門前的小難題,初級(jí)課程。

2.適應(yīng)于無需登錄,明文但需要驗(yàn)證證書才能訪問的頁面。

3.獲取的數(shù)據(jù)類型為HTML文檔。

4.請求方法為Get/Post

3.第三招,根據(jù)URL地址獲取需要登錄才能訪問的網(wǎng)頁信息

我們先來分析一下這種類型的網(wǎng)頁,需要登錄才能訪問的網(wǎng)頁,其它呢也是一種驗(yàn)證,驗(yàn)證什么呢,驗(yàn)證客戶端是否登錄,是否具用相應(yīng)的憑證,需要登錄的都要驗(yàn)證SessionID這是每一個(gè)需要登錄的頁面都需要驗(yàn)證的,那我們怎么做的,我們第一步就是要得存在Cookie里面的數(shù)據(jù)包括SessionID,那怎么得到呢,這個(gè)方法很多,使用ID9或者是火狐瀏覽器很容易就能得到。

提供一個(gè)網(wǎng)頁抓取hao123手機(jī)號(hào)碼歸屬地的例子  這里面針對ID9有詳細(xì)的說明。

如果我們得到了登錄的Cookie信息之后那個(gè)再去訪問相應(yīng)的頁面就會(huì)非常的簡單了,其它說白了就是把本地的Cookie信息在請求的時(shí)候捎帶過去就行了。

看代碼

get方法

/// <summary>
/// 傳入U(xiǎn)RL返回網(wǎng)頁的html代碼帶有證書的方法
/// </summary>
public string GetUrltoHtml(string Url)
{
 StringBuilder content = new StringBuilder();
 try
 {
  // 與指定URL創(chuàng)建HTTP請求
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)";
  request.Method = "GET";
  request.Accept = "*/*";
  //如果方法驗(yàn)證網(wǎng)頁來源就加上這一句如果不驗(yàn)證那就可以不寫了
  request.Referer = "http://txw1958.cnblogs.com";
  CookieContainer objcok = new CookieContainer();
  objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("鍵", "值"));
  objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("鍵", "值"));
  objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233"));
  request.CookieContainer = objcok;
  //不保持連接
  request.KeepAlive = true;
  // 獲取對應(yīng)HTTP請求的響應(yīng)
  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  // 獲取響應(yīng)流
  Stream responseStream = response.GetResponseStream();
  // 對接響應(yīng)流(以"GBK"字符集)
  StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312"));
  // 開始讀取數(shù)據(jù)
  Char[] sReaderBuffer = new Char[256];
  int count = sReader.Read(sReaderBuffer, 0, 256);
  while (count > 0)
  {
   String tempStr = new String(sReaderBuffer, 0, count);
   content.Append(tempStr);
   count = sReader.Read(sReaderBuffer, 0, 256);
  }
  // 讀取結(jié)束
  sReader.Close();
 }
 catch (Exception)
 {
  content = new StringBuilder("Runtime Error");
 }
 return content.ToString();
}

post方法。

///<summary>
///采用https協(xié)議訪問網(wǎng)絡(luò)
///</summary>
public string OpenReadWithHttps(string URL, string strPostdata)
{
 Encoding encoding = Encoding.Default;
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
 request.Method = "post";
 request.Accept = "text/html, application/xhtml+xml, */*";
 request.ContentType = "application/x-www-form-urlencoded";
 CookieContainer objcok = new CookieContainer();
 objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("鍵", "值"));
 objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("鍵", "值"));
 objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233"));
 request.CookieContainer = objcok;
 byte[] buffer = encoding.GetBytes(strPostdata);
 request.ContentLength = buffer.Length;
 request.GetRequestStream().Write(buffer, 0, buffer.Length);
 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
 return reader.ReadToEnd();
}

特點(diǎn):

1.還算有點(diǎn)水類型的,練習(xí)成功后可以小牛一把。

2.適應(yīng)于需要登錄才能訪問的頁面。

3.獲取的數(shù)據(jù)類型為HTML文檔。

4.請求方法為Get/Post

總結(jié)一下,其它基本的技能就這幾個(gè)部分,如果再深入的話那就是基本技能的組合了

比如,

1. 先用Get或者Post方法登錄然后取得Cookie再去訪問頁面得到信息,這種其它也是上面技能的組合,這里需要以請求后做這樣一步。response.Cookie

這就是在你請求后可以得到當(dāng)次Cookie的方法,直接取得返回給上一個(gè)方法使用就行了,上面我們都是自己構(gòu)造的,在這里直接使用這個(gè)Cookie就可以了。

2.如果我們碰到需要登錄而且還要驗(yàn)證證書的網(wǎng)頁怎么辦,其它這個(gè)也很簡單把我們上面的方法綜合 一下就行了,如下代碼這里我以Get為例子Post例子也是同樣的方法

/// <summary>
/// 傳入U(xiǎn)RL返回網(wǎng)頁的html代碼
/// </summary>
public string GetUrltoHtml(string Url)
{
 StringBuilder content = new StringBuilder();
 try
 {
  //這一句一定要寫在創(chuàng)建連接的前面。使用回調(diào)的方法進(jìn)行證書驗(yàn)證。
  ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
  // 與指定URL創(chuàng)建HTTP請求
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  //創(chuàng)建證書文件
  X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer");
  //添加到請求里
  request.ClientCertificates.Add(objx509);
  CookieContainer objcok = new CookieContainer();
  objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("鍵", "值"));
  objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("鍵", "值"));
  objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233"));
  request.CookieContainer = objcok;
  // 獲取對應(yīng)HTTP請求的響應(yīng)
  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  // 獲取響應(yīng)流
  Stream responseStream = response.GetResponseStream();
  // 對接響應(yīng)流(以"GBK"字符集)
  StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
  // 開始讀取數(shù)據(jù)
  Char[] sReaderBuffer = new Char[256];
  int count = sReader.Read(sReaderBuffer, 0, 256);
  while (count > 0)
  {
   String tempStr = new String(sReaderBuffer, 0, count);
   content.Append(tempStr);
   count = sReader.Read(sReaderBuffer, 0, 256);
  }
  // 讀取結(jié)束
  sReader.Close();
 }
 catch (Exception)
 {
  content = new StringBuilder("Runtime Error");
 }
 return content.ToString();
}

3.如果我們碰到那種需要驗(yàn)證網(wǎng)頁來源的方法應(yīng)該怎么辦呢,這種情況其它是有些程序員會(huì)想到你可能會(huì)使用程序,自動(dòng)來獲取網(wǎng)頁信息,為了防止就使用頁面來源來驗(yàn)證,就是說只要不是從他們所在頁面或是域名過來的請求就不接受,有的是直接驗(yàn)證來源的IP,這些都可以使用下面一句來進(jìn)入,這主要是這個(gè)地址是可以直接偽造的

request.Referer = <a href=//www.jb51.net>//www.jb51.net</a>;

呵呵其它很簡單因?yàn)檫@個(gè)地址可以直接修改。但是如果服務(wù)器上驗(yàn)證的是來源的URL那就完了,我們就得去修改數(shù)據(jù)包了,這個(gè)有點(diǎn)難度暫時(shí)不討論。

4.提供一些與這個(gè)例子相配置的方法

過濾HTML標(biāo)簽的方法

/// <summary>
/// 過濾html標(biāo)簽
/// </summary>
public static string StripHTML(string stringToStrip)
{
 // paring using RegEx   //
 stringToStrip = Regex.Replace(stringToStrip, "</p(?:\\s*)>(?:\\s*)<p(?:\\s*)>", "\n\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
 stringToStrip = Regex.Replace(stringToStrip, "
", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
 stringToStrip = Regex.Replace(stringToStrip, "\"", "''", RegexOptions.IgnoreCase | RegexOptions.Compiled);
 stringToStrip = StripHtmlXmlTags(stringToStrip);
 return stringToStrip;
}
private static string StripHtmlXmlTags(string content)
{
 return Regex.Replace(content, "<[^>]+>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
}

URL轉(zhuǎn)化的方法

#region 轉(zhuǎn)化 URL
public static string URLDecode(string text)
{
 return HttpUtility.UrlDecode(text, Encoding.Default);
}
public static string URLEncode(string text)
{
 return HttpUtility.UrlEncode(text, Encoding.Default);
}
#endregion

提供一個(gè)實(shí)際例子,這個(gè)是使用IP138來查詢手機(jī)號(hào)碼歸屬地的方法,其它在我的上一次文章里都有,在這里我再放上來是方便大家閱讀,這方面的技術(shù)其它研究起來很有意思,希望大家多提建議,我相信應(yīng)該還有更多更好,更完善的方法,在這里給大家提供一個(gè)參考吧。感謝支持

上例子

/// <summary>
/// 輸入手機(jī)號(hào)碼得到歸屬地信息
/// </summary>
/// <returns>數(shù)組類型0為歸屬地,1卡類型,2區(qū) 號(hào),3郵 編</returns>
public static string[] getTelldate(string number)
{
 try
 {
  string strSource = GetUrltoHtml("http://www.ip138.com:8080/search.asp?action=mobile&mobile=" + number.Trim());
  //歸屬地
  strSource = strSource.Substring(strSource.IndexOf(number));
  strSource = StripHTML(strSource);
  strSource = strSource.Replace("\r", "");
  strSource = strSource.Replace("\n", "");
  strSource = strSource.Replace("\t", "");
  strSource = strSource.Replace(" ", "");
  strSource = strSource.Replace("-->", "");
  string[] strnumber = strSource.Split(new string[] { "歸屬地", "卡類型", "郵 編", "區(qū) 號(hào)", "更詳細(xì)", "卡號(hào)" }, StringSplitOptions.RemoveEmptyEntries);
  string[] strnumber1 = null;
  if (strnumber.Length > 4)
  {
   strnumber1 = new string[] { strnumber[1].Trim(), strnumber[2].Trim(), strnumber[3].Trim(), strnumber[4].Trim() };
  }
  return strnumber1;
 }
 catch (Exception)
 {
  return null;
 }
}

這個(gè)例子寫是不怎么樣,些地方是可以簡化的,這個(gè)接口而且可以直接使用Xml得到,但我在這里的重點(diǎn)是讓一些新手看看方法和思路風(fēng)涼啊,呵呵

第四招,通過Socket訪問

///<summary>
/// 請求的公共類用來向服務(wù)器發(fā)送請求
///</summary>
///<param name="strSMSRequest">發(fā)送請求的字符串</param>
///<returns>返回的是請求的信息</returns>
private static string SMSrequest(string strSMSRequest)
{
 byte[] data = new byte[1024];
 string stringData = null;
 IPHostEntry gist = Dns.GetHostByName("www.110.cn");
 IPAddress ip = gist.AddressList[0];
 //得到IP 
 IPEndPoint ipEnd = new IPEndPoint(ip, 3121);
 //默認(rèn)80端口號(hào) 
 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 //使用tcp協(xié)議 stream類型 
 try
 {
  socket.Connect(ipEnd);
 }
 catch (SocketException ex)
 {
  return "Fail to connect server\r\n" + ex.ToString();
 }
 string path = strSMSRequest.ToString().Trim();
 StringBuilder buf = new StringBuilder();
 //buf.Append("GET ").Append(path).Append(" HTTP/1.0\r\n");
 //buf.Append("Content-Type: application/x-www-form-urlencoded\r\n");
 //buf.Append("\r\n");
 byte[] ms = System.Text.UTF8Encoding.UTF8.GetBytes(buf.ToString());
 //提交請求的信息
 socket.Send(ms);
 //接收返回 
 string strSms = "";
 int recv = 0;
 do
 {
  recv = socket.Receive(data);
  stringData = Encoding.ASCII.GetString(data, 0, recv);
  //如果請求的頁面meta中指定了頁面的encoding為gb2312則需要使用對應(yīng)的Encoding來對字節(jié)進(jìn)行轉(zhuǎn)換() 
  strSms = strSms + stringData;
  //strSms += recv.ToString();
 }
 while (recv != 0);
 socket.Shutdown(SocketShutdown.Both);
 socket.Close();
 return strSms;
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。

上一篇:Winform窗體圓角設(shè)計(jì)代碼

欄    目:C#教程

下一篇:C#使用Windows Service的簡單教程(創(chuàng)建、安裝、卸載、調(diào)試)

本文標(biāo)題:淺談C#中HttpWebRequest與HttpWebResponse的使用方法

本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/6043.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有