HttpWebRequest和HttpWebResponse用法小結(jié)
更新時(shí)間:2011年09月26日 21:00:23 作者:
在每個(gè)系統(tǒng)出寫(xiě)入報(bào)告錯(cuò)誤代碼(找個(gè)合理的理由,比如系統(tǒng)免費(fèi)升級(jí)) -> 自家服務(wù)器接收并處理錯(cuò)誤報(bào)告 -> 反饋用戶(解決掉BUG就行,不要太聲揚(yáng))
最近公司拓展市場(chǎng)異常迅猛,數(shù)周之類開(kāi)出去幾十套系統(tǒng),雖然系統(tǒng)名字不一樣,但各個(gè)內(nèi)容相似。由于時(shí)間緊迫,很多開(kāi)出去的系統(tǒng)
出現(xiàn)各種神奇的錯(cuò)誤,當(dāng)初雖然有記錄錯(cuò)誤日志,然而很多客戶使用的是自己的服務(wù)器和數(shù)據(jù)庫(kù),出了問(wèn)題我們并不能立即掌握信息,
因此決定做一個(gè)捕獲所有系統(tǒng)的異常并保存到自家數(shù)據(jù)庫(kù)中。
實(shí)現(xiàn)思路
在每個(gè)系統(tǒng)出寫(xiě)入報(bào)告錯(cuò)誤代碼(找個(gè)合理的理由,比如系統(tǒng)免費(fèi)升級(jí)) -> 自家服務(wù)器接收并處理錯(cuò)誤報(bào)告 -> 反饋用戶(解決掉BUG就行,不要太聲揚(yáng))
基礎(chǔ)回顧
---參考msdn
1.HttpWebRequest類:提供WebRequest類的Http特定的實(shí)現(xiàn)。
HttpWebRequest 類對(duì) WebRequest 中定義的屬性和方法提供支持,也對(duì)使用戶能夠直接與使用 HTTP 的服務(wù)器交互的附加屬性和方法提供支持。
不要使用構(gòu)造函數(shù)創(chuàng)建HttpWebRequest實(shí)例,請(qǐng)使用System.Net.WebRequest.Create(URI uriString)來(lái)創(chuàng)建實(shí)例,如果URI是Http://或Https://,
返回的是HttpWebRequest對(duì)象。(建立請(qǐng)求特定URI的對(duì)象)
當(dāng)向資源發(fā)送數(shù)據(jù)時(shí),GetRequestStream方法返回用于發(fā)送數(shù)據(jù)的Stream對(duì)象。(獲取請(qǐng)求數(shù)據(jù)的流對(duì)象)
GetResponse方法向RequestUri屬性指定的資源發(fā)出同步請(qǐng)求并返回包含該響應(yīng)的HttpWebResponse。(獲取來(lái)自internet的響應(yīng))
實(shí)例講解
1.遠(yuǎn)程請(qǐng)求并返回響應(yīng)
/// <summary>
/// 報(bào)告系統(tǒng)錯(cuò)誤
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
public static string Sys_ReportError(Exception ex)
{
try
{
//要提交表單的URI字符串
string uriString = "http://localhost/Sys_ReportError.aspx";
HttpContext context = HttpContext.Current;
if (context == null) return string.Empty;
string targetSite = ex.TargetSite.ToString();
string stackTrace = ex.StackTrace;
string friendlyMsg = ex.Message;
string errorPage = context == null || context.Request == null ? "" : context.Request.Url.ToString();
string projectName = Config.Sys_Title();
//要提交的字符串?dāng)?shù)據(jù)
string postString = "targetSite=" + HttpUtility.UrlEncode(targetSite);
postString += "&stackTrace=" + HttpUtility.UrlEncode(stackTrace);
postString += "&friendlyMsg=" + HttpUtility.UrlEncode(friendlyMsg);
postString += "&errorPage=" + HttpUtility.UrlEncode(errorPage);
postString += "&projectName=" + HttpUtility.UrlEncode(projectName);
postString += "&key=" + "";
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
webRequest = System.Net.WebRequest.Create(uriString) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 1000 * 60;
webRequest.ContentType = "application/x-www-form-urlencoded";
//POST the data.
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postString);
}
catch (Exception ex2)
{
return "連接錯(cuò)誤";
}
finally
{
requestWriter.Close();
requestWriter = null;
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
catch
{
return "未知錯(cuò)誤";
}
}
/// <summary>
/// Process the web response.
/// </summary>
/// <param name="webRequest">The request object.</param>
/// <returns>The response data.</returns>
public static string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
return "連接錯(cuò)誤";
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
2.遠(yuǎn)程服務(wù)器讀取流
_context = HttpContext.Current;
Stream stream = _context.Request.InputStream; //獲取當(dāng)前傳入Http輸入流
long length = stream.Length;
byte[] data = _context.Request.BinaryRead((int)length);//對(duì)當(dāng)前輸入流進(jìn)行指定字節(jié)數(shù)的二進(jìn)制讀取
string strContent = Encoding.UTF8.GetString(data);//解碼為UTF8編碼形式的字符串
代碼講解到此結(jié)束,一些相關(guān)補(bǔ)充:
1.HttpWebRequest對(duì)象有一些相關(guān)設(shè)置屬性,如Method(發(fā)送方式),TimeOut(請(qǐng)求超時(shí)時(shí)間),ContentType(Http標(biāo)頭的值)等等。
2.若遠(yuǎn)程接收頁(yè)面出錯(cuò),該如何調(diào)試,很簡(jiǎn)單,只需寫(xiě)入下面的代碼:
HttpWebResponse res = null;
WebResponse response = null;
try
{
WebResponse response = webRequest.GetResponse();
}
catch (WebException ex1)
{
res = (HttpWebResponse)ex1.Response;
}
finally
{
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string strhtml = sr.ReadToEnd();
HttpContext.Current.Response.Write(strhtml);
}
當(dāng)獲取服務(wù)器響應(yīng)出錯(cuò)時(shí),捕捉錯(cuò)誤,最終打印出錯(cuò)誤即可。
出現(xiàn)各種神奇的錯(cuò)誤,當(dāng)初雖然有記錄錯(cuò)誤日志,然而很多客戶使用的是自己的服務(wù)器和數(shù)據(jù)庫(kù),出了問(wèn)題我們并不能立即掌握信息,
因此決定做一個(gè)捕獲所有系統(tǒng)的異常并保存到自家數(shù)據(jù)庫(kù)中。
實(shí)現(xiàn)思路
在每個(gè)系統(tǒng)出寫(xiě)入報(bào)告錯(cuò)誤代碼(找個(gè)合理的理由,比如系統(tǒng)免費(fèi)升級(jí)) -> 自家服務(wù)器接收并處理錯(cuò)誤報(bào)告 -> 反饋用戶(解決掉BUG就行,不要太聲揚(yáng))
基礎(chǔ)回顧
---參考msdn
1.HttpWebRequest類:提供WebRequest類的Http特定的實(shí)現(xiàn)。
HttpWebRequest 類對(duì) WebRequest 中定義的屬性和方法提供支持,也對(duì)使用戶能夠直接與使用 HTTP 的服務(wù)器交互的附加屬性和方法提供支持。
不要使用構(gòu)造函數(shù)創(chuàng)建HttpWebRequest實(shí)例,請(qǐng)使用System.Net.WebRequest.Create(URI uriString)來(lái)創(chuàng)建實(shí)例,如果URI是Http://或Https://,
返回的是HttpWebRequest對(duì)象。(建立請(qǐng)求特定URI的對(duì)象)
當(dāng)向資源發(fā)送數(shù)據(jù)時(shí),GetRequestStream方法返回用于發(fā)送數(shù)據(jù)的Stream對(duì)象。(獲取請(qǐng)求數(shù)據(jù)的流對(duì)象)
GetResponse方法向RequestUri屬性指定的資源發(fā)出同步請(qǐng)求并返回包含該響應(yīng)的HttpWebResponse。(獲取來(lái)自internet的響應(yīng))
實(shí)例講解
1.遠(yuǎn)程請(qǐng)求并返回響應(yīng)
復(fù)制代碼 代碼如下:
/// <summary>
/// 報(bào)告系統(tǒng)錯(cuò)誤
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
public static string Sys_ReportError(Exception ex)
{
try
{
//要提交表單的URI字符串
string uriString = "http://localhost/Sys_ReportError.aspx";
HttpContext context = HttpContext.Current;
if (context == null) return string.Empty;
string targetSite = ex.TargetSite.ToString();
string stackTrace = ex.StackTrace;
string friendlyMsg = ex.Message;
string errorPage = context == null || context.Request == null ? "" : context.Request.Url.ToString();
string projectName = Config.Sys_Title();
//要提交的字符串?dāng)?shù)據(jù)
string postString = "targetSite=" + HttpUtility.UrlEncode(targetSite);
postString += "&stackTrace=" + HttpUtility.UrlEncode(stackTrace);
postString += "&friendlyMsg=" + HttpUtility.UrlEncode(friendlyMsg);
postString += "&errorPage=" + HttpUtility.UrlEncode(errorPage);
postString += "&projectName=" + HttpUtility.UrlEncode(projectName);
postString += "&key=" + "";
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
webRequest = System.Net.WebRequest.Create(uriString) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 1000 * 60;
webRequest.ContentType = "application/x-www-form-urlencoded";
//POST the data.
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postString);
}
catch (Exception ex2)
{
return "連接錯(cuò)誤";
}
finally
{
requestWriter.Close();
requestWriter = null;
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
catch
{
return "未知錯(cuò)誤";
}
}
復(fù)制代碼 代碼如下:
/// <summary>
/// Process the web response.
/// </summary>
/// <param name="webRequest">The request object.</param>
/// <returns>The response data.</returns>
public static string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
return "連接錯(cuò)誤";
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
2.遠(yuǎn)程服務(wù)器讀取流
復(fù)制代碼 代碼如下:
_context = HttpContext.Current;
Stream stream = _context.Request.InputStream; //獲取當(dāng)前傳入Http輸入流
long length = stream.Length;
byte[] data = _context.Request.BinaryRead((int)length);//對(duì)當(dāng)前輸入流進(jìn)行指定字節(jié)數(shù)的二進(jìn)制讀取
string strContent = Encoding.UTF8.GetString(data);//解碼為UTF8編碼形式的字符串
代碼講解到此結(jié)束,一些相關(guān)補(bǔ)充:
1.HttpWebRequest對(duì)象有一些相關(guān)設(shè)置屬性,如Method(發(fā)送方式),TimeOut(請(qǐng)求超時(shí)時(shí)間),ContentType(Http標(biāo)頭的值)等等。
2.若遠(yuǎn)程接收頁(yè)面出錯(cuò),該如何調(diào)試,很簡(jiǎn)單,只需寫(xiě)入下面的代碼:
復(fù)制代碼 代碼如下:
HttpWebResponse res = null;
WebResponse response = null;
try
{
WebResponse response = webRequest.GetResponse();
}
catch (WebException ex1)
{
res = (HttpWebResponse)ex1.Response;
}
finally
{
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string strhtml = sr.ReadToEnd();
HttpContext.Current.Response.Write(strhtml);
}
當(dāng)獲取服務(wù)器響應(yīng)出錯(cuò)時(shí),捕捉錯(cuò)誤,最終打印出錯(cuò)誤即可。
相關(guān)文章
為HttpClient添加默認(rèn)請(qǐng)求報(bào)頭的四種解決方案
這篇文章主要給大家介紹了關(guān)于為HttpClient添加默認(rèn)請(qǐng)求報(bào)頭的四種解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用HttpClient具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
ASP.NET2.0 SQL Server數(shù)據(jù)庫(kù)連接詳解
本文將詳細(xì)介紹如何使用Connection對(duì)象連接數(shù)據(jù)庫(kù) 。對(duì)于不同的.NET 數(shù)據(jù)提供者,ADO.NET采用不同的Connection對(duì)象連接數(shù)據(jù)庫(kù)。這些Connection對(duì)象為我們屏蔽了具體的實(shí)現(xiàn)細(xì)節(jié),并提供了一種統(tǒng)一的實(shí)現(xiàn)方法。2009-07-07
SQL為查詢的結(jié)果加上序號(hào)(ROW_NUMBER) 合并多個(gè)查詢結(jié)果
SQL為查詢的結(jié)果加上序號(hào)(ROW_NUMBER) 合并多個(gè)查詢結(jié)果2010-03-03
RadioButtonList綁定圖片及泛型Dictionary應(yīng)用
讀取站點(diǎn)某一目錄的圖片,需要掌握LINQ與泛型Dictionary<TKey,TValue>的使用,本文將介紹RadioButtonList綁定圖片的實(shí)現(xiàn),感興趣的朋友可以了解下,或許對(duì)你有所幫助2013-02-02
asp.net 服務(wù)器控件的 ID,ClientID,UniqueID 的區(qū)別
asp.net 服務(wù)器控件的 ID,ClientID,UniqueID 的區(qū)別分析,需要的朋友可以參考下。2010-04-04
.NET 6開(kāi)發(fā)之實(shí)現(xiàn)緩存過(guò)程詳解
有的時(shí)候?yàn)榱藴p少客戶端請(qǐng)求相同資源的邏輯重復(fù)執(zhí)行,我們會(huì)考慮使用一些緩存的方式。這篇文章主要就介紹了在.NET 6開(kāi)發(fā)中如何實(shí)現(xiàn)緩存,感興趣的可以學(xué)習(xí)一下2022-01-01

