HttpWebRequest and HttpWebResponse Usage Summary _ Practical skills

Source: Internet
Author: User
Tags httpcontext urlencode
Recently, the company to expand the market unusually fast, weeks and so on to open dozens of sets of systems, although the system name is not the same, but the contents of similar. Because of the time constraints, many of the system to open out
There are a variety of magical errors, although the original record error log, but many customers use their own servers and databases, out of the problem we can not immediately grasp the information,
So decide to make an exception to capture all the systems and save it to your own database.
Realize the idea
Write report error codes in each system (for a reasonable reason, such as a free upgrade of the system)-> your own server to receive and process error reports-> feedback users (solve the bug on the line, not too Sangyan)
Basic Review
---reference MSDN
1.HttpWebRequest class: Provides HTTP-specific implementations of the WebRequest class.
The HttpWebRequest class provides support for the properties and methods defined in WebRequest, as well as additional properties and methods that enable users to interact directly with servers that use HTTP.
Do not use constructors to create HttpWebRequest instances, use System.Net.WebRequest.Create (URI uristring) to create an instance, if the URI is http://or https://,
Returns the HttpWebRequest object. (Creates an object that requests a specific URI)
When you send data to a resource, the GetRequestStream method returns the stream object used to send the data. (Gets the stream object that requested the data)
The GetResponse method issues a synchronization request to the resource specified by the RequestUri property and returns the HttpWebResponse that contains the response. (Get responses from the Internet)
Example explanation
1. Remote Request and return response
Copy Code code as follows:

<summary>
Reporting System Errors
</summary>
<param name= "Ex" ></param>
<returns></returns>
public static string Sys_reporterror (Exception ex)
{
Try
{
URI string to submit form
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 submit
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 Code code 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. Remote server Read stream
Copy Code code as follows:

_context = HttpContext.Current;
Stream stream = _context. Request.inputstream; Gets the current incoming HTTP input stream
Long length = stream. Length;
byte[] data = _context. Request.BinaryRead ((int) length);//binary read of the specified number of bytes for the current input stream
String strcontent = Encoding.UTF8.GetString (data);//strings decoded to UTF8 encoded form

The code explains the end, some related additions:
1.HttpWebRequest objects have some settings properties, 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:
Copy Code code 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 getting the server response error, catch the error and finally print out the error.

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.