Use of the HttpWebRequest class and WebRequest class

Source: Internet
Author: User
Tags servervariables

1. System. Net. HttpWebRequest class
Http://msdn.microsoft.com/library/chs/default.asp? Url =/library/CHS/cpref/html/frlrfsystemnetwebrequestclasstopic. asp

The following code sends data in Post mode:
Using System. IO;
Using System. Net;
Using System. Text;
Using System. Text. RegularExpressions;

Private void btnConfirm_Click (object sender, System. EventArgs e)
{
String UserName = txtUserName. Text;
String SpotID = txtSpotID. Text;
String BBS = txtBBS. Text;
String Board = txtBoard. Text;
String Title = txtTitle. Text;
String Content = txtContent. Text;
Content = NoHTML (Content); // remove HTML tags
String UserIp = Request. ServerVariables ["REMOTE_HOST"]. ToString ();
String PostUrl = "";
String PostDateTime = DateTime. Now. ToString ();

String WebSite = ""; // server receiving page
WebSite = System. Configuration. ConfigurationSettings. receivettings ["PostUrl"];

String strQuery = "UserName =" + UserName + "& SpotID =" + SpotID + "& BBS =" + BBS + "& Board =" + Board +
"& Title =" + Title + "& Content =" + Content + "& UserIp =" + UserIp + "& PostUrl =" + PostUrl + "& PostDateTime =" + PostDateTime; // data parameter queue
Encoding encoding = Encoding. UTF8;
Byte [] data = encoding. GetBytes (strQuery );

// Prepare the request...
HttpWebRequest myRequest = (HttpWebRequest) WebRequest. Create (WebSite );
MyRequest. Method = "POST ";
MyRequest. ContentType = "application/x-www-form-urlencoded ";
MyRequest. ContentLength = data. Length;
Stream newStream = myRequest. GetRequestStream ();
// Send data
NewStream. Write (data, 0, data. Length );
NewStream. Close ();

Page. RegisterStartupScript ("script", GetShowAlert ("published successfully! "," Window. location. href ('clientpostnote. aspx ');"));
}

/// <Summary>
/// Remove HTML tags
/// </Summary>
/// <Param name = "Htmlstring"> including the source code of HTML </param>
/// <Returns> removed text </returns>
Public string NoHTML (string Htmlstring)
{
// Delete the script
Htmlstring = Htmlstring. Replace ("\ r \ n ","");
Htmlstring = Regex. Replace (Htmlstring, @ "<script .*? </Script> "," ", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "<style .*? </Style> "," ", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "<. *?> "," ", RegexOptions. IgnoreCase );
// Delete HTML
Htmlstring = Regex. Replace (Htmlstring, @ "<(. [^>] *)>", "", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "([\ r \ n]) [\ s] +", "", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "-->", "", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "<! --. * "," ", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "& (quot | #34);", "\" ", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "& (amp | #38);", "&", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "& (lt | #60);", "<", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "& (gt | #62);", ">", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "& (nbsp | #160);", "", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "& (iexcl | #161);", "\ xa1", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "& (cent | #162);", "\ xa2", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "& (pound | #163);", "\ xa3", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "& (copy | #169);", "\ xa9", RegexOptions. IgnoreCase );
Htmlstring = Regex. Replace (Htmlstring, @ "(\ d +);", "", RegexOptions. IgnoreCase );
Htmlstring = Htmlstring. Replace ("<","");
Htmlstring = Htmlstring. Replace ("> ","");
Htmlstring = Htmlstring. Replace ("\ r \ n ","");
Htmlstring = HttpContext. Current. Server. HtmlEncode (Htmlstring). Trim ();
Return Htmlstring;
}

Public string GetShowAlert (string info, string action)
{
String strScript = String. Empty;
StrScript = "<script language = javascript> \ r \ n ";
StrScript + = "document. onreadystatechange = ShowAlert; \ r \ n ";
StrScript + = "function ShowAlert () \ r \ n ";
StrScript + = "{\ r \ n ";
StrScript + = "if (document. readyState = \" complete \ ") \ r \ n ";
StrScript + = "{\ r \ n ";
StrScript + = "alert ('" + info. replace ("'",""). replace ("\ n ",""). replace ("\ r", "") + "'); \ r \ n ";
If (action. Length> 0)
{
If (action [action. Length-1]! = ';')
Action = action + ";";
StrScript + = action + "\ r \ n ";
}
StrScript + = "} \ r \ n ";
StrScript + = "} \ r \ n ";
StrScript + = "</script> ";
Return strScript;
}

2. System. Net. WebRequest class
Http://msdn.microsoft.com/library/chs/default.asp? Url =/library/CHS/cpref/html/frlrfsystemnetwebrequestclasstopic. asp

The following code sends data asynchronously in Get mode:
Using System. IO;
Using System. Net;
Using System. Text. RegularExpressions;
Private void btnConfirm_Click (object sender, System. EventArgs e)
{
String UserName = txtUserName. Text;
String SpotID = txtSpotID. Text;
String BBS = txtBBS. Text;
String Board = txtBoard. Text;
String Title = txtTitle. Text;
String Content = NoHTML (txtContent. Text );
String UserIp = Request. ServerVariables ["REMOTE_HOST"]. ToString ();
String PostUrl = "";
String PostDateTime = DateTime. Now. ToString ();

String noteinfo = ""; // post content
Noteinfo = "post content :"
+ "\ R \ n UserName:" + UserName + "\ r \ n Website:" + SpotID + "\ r \ n Forum:" + BBS
+ "\ R \ n Forum:" + Board + "\ r \ n Title:" + Title + "\ r \ n Content:" + Content
+ "\ R \ n IP:" + UserIp + "\ r \ n URL:" + PostUrl + "\ r \ n ";

String WebSite = ""; // server receiving page
WebSite = System. Configuration. ConfigurationSettings. receivettings ["PostUrl"];
String Parameters = "UserName; SpotID; BBS; Board; Title; Content; UserIp; PostUrl; PostDateTime ";
String ParameterValues = UserName + ";" + SpotID + ";" + BBS + ";" + Board + ";" + Title + ";" + Content + "; "+ UserIp +"; "+ PostUrl +"; "+ PostDateTime;

BLLPostData (noteinfo, WebSite, Parameters, ParameterValues); // asynchronous Post Data

Page. RegisterStartupScript ("script", GetShowAlert ("published successfully! "," Window. location. href ('addnotenet. aspx ');"));
}

Public void BLLPostData (string noteinfo, string WebSite, string Parameters, string ParameterValues)
{
BLLPostDataDeal (noteinfo, WebSite, Parameters, ParameterValues );
}
/// <Summary>
/// Asynchronous Post Data
/// </Summary>
Private void BLLPostDataDeal (string noteinfo, string WebSite, string Parameters, string ParameterValues)
{
AsyncPostDataDeal asynci = new AsyncPostDataDeal (AsPostDataDeal );
// AsyncCallback cb = new AsyncCallback (Results );
// IAsyncResult ar = asynci. BeginInvoke (PhoneNo, LoginName, Mobile, CusID, XMLData, cb, asynci );

// No callback delegate is provided when asynchronous calls are started.
IAsyncResult ar = asynci. BeginInvoke (noteinfo, WebSite, Parameters, ParameterValues, null, asynci );
}
Public delegate void AsyncPostDataDeal (string noteinfo, string WebSite, string Parameters, string ParameterValues );
Private void AsPostDataDeal (string noteinfo, string WebSite, string Parameters, string ParameterValues)
{
String msg = ""; // log
Try
{
If (WebSite! = "")
{
String RegResult = ""; // receives the returned value
RegResult = ConnectToWebSite2 (WebSite, Parameters, ParameterValues );
// Int IsSuccess =-1; // receiving status

If (RegResult = "Y ")
{
// IsSuccess = 1;
Msg = DateTime. Now. ToString () + "post transfer successful! \ R \ n "+ noteinfo;
Log (msg );
}
Else if (RegResult = "N ")
{
// IsSuccess = 0;
Msg = DateTime. Now. ToString () + "data insertion error. Transmission failed! \ R \ n "+ noteinfo;
Log (msg );
}
Else if (RegResult = "F ")
{
// IsSuccess = 2;
Msg = DateTime. Now. ToString () + "An error occurred on the server and the transfer failed! \ R \ n "+ noteinfo;
Log (msg );
}
}
Else
{
Msg = DateTime. Now. ToString () + "the transmission URL is not obtained. Transmission cannot continue! \ R \ n "+ noteinfo;
Log (msg );
}
}
Catch (Exception ex)
{
Msg = DateTime. Now. ToString () + "transmission failed! The error is as follows: "+ ex. Message +" \ r \ n "+ noteinfo;
Log (msg );
}
}

/// <Summary>
/// Use the specified parameter (";") to access the specified URL
/// </Summary>
/// <Param name = ""> </param>
/// <Param name = "parameter name"> </param>
/// <Param name = "parameter value"> </param>
/// <Returns> </returns>
Public string ConnectToWebSite2 (string Web, string Parameters, string ParameterValues)
{
String sPageText = "";

Stream responseStream = null;
StreamReader reader = null;

Web + = "? 1 = 1 ";

If (Parameters. Trim () = "" | ParameterValues. Trim () = "")
{
Log ("the parameter or parameter value is not specified. Please confirm! ");
}
Else
{
String Delimeter = ";";
String [] aryParm = Parameters. Split (Delimeter. ToCharArray ());
String [] aryParmValue = ParameterValues. Split (Delimeter. ToCharArray ());

If (aryParm. Length! = AryParmValue. Length)
{
Log ("the number of parameters and the number of parameter values are not equal. Please confirm! ");
}
Else
{
For (int I = 0; I <aryParm. Length; I ++)
{
AryParmValue [I] = System. Web. HttpUtility. UrlEncode (aryParmValue [I]. ToString ());
Web + = "&" + aryParm [I]. Trim () + "=" + aryParmValue [I]. Trim ();
}
System. Uri RegUri = new Uri (Web );
WebRequest request = WebRequest. Create (RegUri );
WebResponse response = request. GetResponse ();
Try
{
ResponseStream = response. GetResponseStream ();
Reader = new StreamReader (responseStream, System. Text. Encoding. Default );
SPageText = reader. ReadToEnd ();
}
Finally
{
Reader. Close ();
ResponseStream. Close ();
Response. Close ();
}
}
}
Return sPageText;
}

Public void Log (string logText)
{
String strPath = AppDomain. CurrentDomain. BaseDirectory + @ "\ Log ";
If (! System. IO. Directory. Exists (strPath ))
{
System. IO. Directory. CreateDirectory (strPath );
}

StreamWriter sw = null;
String fileName = strPath + @ "\ log.txt ";
If (File. Exists (fileName ))
{
Sw = File. AppendText (fileName );
}
Else
{
Sw = new StreamWriter (fileName );
}
Sw. WriteLine (logText );
Sw. Close ();
}

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.