HttpWebRequest and HttpWebResponse usage Summary

Source: Internet
Author: User

Recently, the company's market expansion has been very fast, and dozens of systems have been launched for weeks. Although the system names are different, the contents are similar. Due to time constraints, many open systems
Despite the original error logs, many customers use their own servers and databases. If something goes wrong, we cannot grasp the information immediately,
Therefore, we decided to capture all system exceptions and save them to our own database.
Implementation
Write the report error code in each system (find a reasonable reason, such as free system upgrade)-> receive and handle the error report on your server-> feedback to the user (just remove the BUG,)
Basic Review
--- Refer to msdn
1. HttpWebRequest class: provides Http-specific implementations of the WebRequest class.
The HttpWebRequest class supports the attributes and methods defined in WebRequest and the additional attributes and methods that allow users to directly interact with servers using HTTP.
Do not use constructors to Create an HttpWebRequest instance. Use System. Net. WebRequest. Create (URI uriString) to Create an instance. If the URI is Http: // or Https ://,
The returned result is an HttpWebRequest object. (Create an object for a specific URI of the request)
When sending data to a resource, the GetRequestStream method returns the Stream object used to send data. (Stream object for retrieving request data)
The GetResponse method sends a synchronous request to the resource specified by the RequestUri attribute and returns the HttpWebResponse containing the response. (Obtain responses from the internet)
Instance description
1. Remote request and response
Copy codeThe Code is as follows:
/// <Summary>
/// Report system errors
/// </Summary>
/// <Param name = "ex"> </param>
/// <Returns> </returns>
Public static string Sys_ReportError (Exception ex)
{
Try
{
// URI string of the form to be submitted
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 "Unknown error ";
}
}

Copy codeThe Code is as follows:
/// <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.
Copy codeThe Code is as follows:
_ Context = HttpContext. Current;
Stream stream = _ context. Request. InputStream; // obtain the input Http Stream.
Long length = stream. Length;
Byte [] data = _ context. Request. BinaryRead (int) length); // read the specified bytes in binary format of the current input stream.
String strContent = Encoding. UTF8.GetString (data); // decodes a UTF-8 encoded string.

This is the end of the Code:
1. The HttpWebRequest object has some related settings attributes, such as Method (sending Method), TimeOut (request TimeOut), and ContentType (Http header value.
2. If an error occurs in the remote reception page, it is easy to debug the page by writing the following code:
Copy codeThe Code is as follows:
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 an error occurs in the server response, capture the error and print the error.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.