HttpWebRequest和HttpWebResponse用法小结
编程学习 2021-07-04 22:40www.dzhlxh.cn编程入门
在每个系统出写入报告错误代码(找个合理的理由,比如系统免费升级) -> 自家服务器接收并处理错误报告 -> 反馈用户(解决掉BUG就行,不要太声扬)
最近公司拓展市场异常迅猛,数周之类开出去几十套系统,虽然系统名字不一样,但各个内容相似。由于时间紧迫,很多开出去的系统
出现各种神奇的错误,当初虽然有记录错误日志,然而很多客户使用的是自己的服务器和数据库,出了问题我们并不能立即掌握信息,
因此决定做一个捕获所有系统的异常并保存到自家数据库中。
实现思路
在每个系统出写入报告错误代码(找个合理的理由,比如系统免费升级) -> 自家服务器接收并处理错误报告 -> 反馈用户(解决掉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.若远程接收页面出错,该如何调试,很简单,只需写入狼蚁网站SEO优化的代码:
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);
}
当获取服务器响应出错时,捕捉错误,最终打印出错误即可。
出现各种神奇的错误,当初虽然有记录错误日志,然而很多客户使用的是自己的服务器和数据库,出了问题我们并不能立即掌握信息,
因此决定做一个捕获所有系统的异常并保存到自家数据库中。
实现思路
在每个系统出写入报告错误代码(找个合理的理由,比如系统免费升级) -> 自家服务器接收并处理错误报告 -> 反馈用户(解决掉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.若远程接收页面出错,该如何调试,很简单,只需写入狼蚁网站SEO优化的代码:
代码如下:
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);
}
当获取服务器响应出错时,捕捉错误,最终打印出错误即可。