Summary of HttpWebRequest and HttpWebResponse usage

  • 2020-05-12 02:29:04
  • OfStack

Recently, the company's market expansion is extremely rapid, a few weeks and so on out of a few 10 systems, although the system name is not the same, but each content is similar. Due to time constraints, many systems are out
There were all kinds of miraculous errors. Although there were error logs at the beginning, many customers were using their own servers and databases, and we could not grasp the information immediately when something went wrong.
So I decided to do one to catch all system exceptions and save them to my own database.
Implementation approach
Write a report error code to each system (for a good reason, such as a free upgrade) > Your own server receives and processes error reports - > Feedback to users (just solve BUG, don't make too much noise)
Based on review of
msdn - reference
1.HttpWebRequest class: provides an Http specific implementation of the WebRequest class.
The HttpWebRequest class provides support for properties and methods defined in WebRequest, as well as for additional properties and methods that enable users to interact directly with servers using HTTP.
Don't use the constructor to create HttpWebRequest instance, please use the System. Net. WebRequest. Create (URI uriString) to create an instance, if the URI is Http: / / or Https: / /,
The HttpWebRequest object is returned. (creates an object that requests a specific URI)
When data is sent to a resource, the GetRequestStream method returns the Stream object used to send the data. (get the stream object of the request data)
The GetResponse method makes a synchronous request to the resource specified by the RequestUri property and returns the HttpWebResponse containing the response. (get the response from internet)
Instance to explain
1. Remote request and return response
 
/// <summary> 
///  Reporting system errors  
/// </summary> 
/// <param name="ex"></param> 
/// <returns></returns> 
public static string Sys_ReportError(Exception ex) 
{ 
try 
{ 
// To submit the form URI string  
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 data to be submitted  
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 " Connection error "; 
} 
finally 
{ 
requestWriter.Close(); 
requestWriter = null; 
} 
responseData = WebResponseGet(webRequest); 
webRequest = null; 
return responseData; 
} 
catch 
{ 
return " An unknown error "; 
} 
} 

 
/// <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 " Connection error "; 
} 
finally 
{ 
webRequest.GetResponse().GetResponseStream().Close(); 
responseReader.Close(); 
responseReader = null; 
} 
return responseData; 
} 

2. The remote server reads the stream
 
_context = HttpContext.Current; 
Stream stream = _context.Request.InputStream; // Get the current incoming Http The input stream  
long length = stream.Length; 
byte[] data = _context.Request.BinaryRead((int)length);// The number of bytes specified for the current input stream 2 Hexadecimal read  
string strContent = Encoding.UTF8.GetString(data);// Decoding for UTF8 A string in encoded form  

This is the end of the code explanation, 1 related supplement:
1. The HttpWebRequest object has a number of Settings, such as Method(send mode),TimeOut(request timeout),ContentType(Http header value), and so on.
2. If the remote receive page error, how to debug, very simple, just write the following code:
 
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); 
} 

When you get a server response error, catch the error and eventually print out the error.

Related articles: