程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> HttpWebRequest和HttpWebResponse用法小結

HttpWebRequest和HttpWebResponse用法小結

編輯:ASP.NET基礎
最近公司拓展市場異常迅猛,數周之類開出去幾十套系統,雖然系統名字不一樣,但各個內容相似。由於時間緊迫,很多開出去的系統
出現各種神奇的錯誤,當初雖然有記錄錯誤日志,然而很多客戶使用的是自己的服務器和數據庫,出了問題我們並不能立即掌握信息,
因此決定做一個捕獲所有系統的異常並保存到自家數據庫中。
實現思路
在每個系統出寫入報告錯誤代碼(找個合理的理由,比如系統免費升級) -> 自家服務器接收並處理錯誤報告 -> 反饋用戶(解決掉BUG就行,不要太聲揚)
基礎回顧
---參考msdn
1.HttpWebRequest類:提供WebRequest類的Http特定的實現。
HttpWebRequest 類對 WebRequest 中定義的屬性和方法提供支持,也對使用戶能夠直接與使用 HTTP 的服務器交互的附加屬性和方法提供支持。
不要使用構造函數創建HttpWebRequest實例,請使用System.Net.WebRequest.Create(URI uriString)來創建實例,如果URI是Http://或Https://,
返回的是HttpWebRequest對象。(建立請求特定URI的對象)
當向資源發送數據時,GetRequestStream方法返回用於發送數據的Stream對象。(獲取請求數據的流對象)
GetResponse方法向RequestUri屬性指定的資源發出同步請求並返回包含該響應的HttpWebResponse。(獲取來自internet的響應)
實例講解
1.遠程請求並返回響應
復制代碼 代碼如下:
/// <summary>
/// 報告系統錯誤
/// </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();
//要提交的字符串數據
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 "連接錯誤";
}
finally
{
requestWriter.Close();
requestWriter = null;
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
catch
{
return "未知錯誤";
}
}

復制代碼 代碼如下:
/// <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 "連接錯誤";
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}

2.遠程服務器讀取流
復制代碼 代碼如下:
_context = HttpContext.Current;
Stream stream = _context.Request.InputStream; //獲取當前傳入Http輸入流
long length = stream.Length;
byte[] data = _context.Request.BinaryRead((int)length);//對當前輸入流進行指定字節數的二進制讀取
string strContent = Encoding.UTF8.GetString(data);//解碼為UTF8編碼形式的字符串

代碼講解到此結束,一些相關補充:
1.HttpWebRequest對象有一些相關設置屬性,如Method(發送方式),TimeOut(請求超時時間),ContentType(Http標頭的值)等等。
2.若遠程接收頁面出錯,該如何調試,很簡單,只需寫入下面的代碼:
復制代碼 代碼如下:
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);
}

當獲取服務器響應出錯時,捕捉錯誤,最終打印出錯誤即可。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved