HttpWebRequest类与WebRequest类的使用

1、System.Net.HttpWebRequest 类
http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpref/html/frlrfsystemnetwebrequestclasstopic.asp

如下代码以Post方式发送数据:
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);//去除HTML标记
   string UserIp = Request.ServerVariables["REMOTE_HOST"].ToString();   
   string PostUrl = "";
   string PostDateTime = DateTime.Now.ToString();
   
   string WebSite = "";//服务器接收页面
   WebSite = System.Configuration.ConfigurationSettings.AppSettings["PostUrl"];

   string strQuery = "UserName="+ UserName +"&SpotID="+ SpotID +"&BBS="+ BBS +"&Board="+ Board +
    "&Title="+ Title +"&Content="+ Content +"&UserIp="+ UserIp +"&PostUrl="+ PostUrl +"&PostDateTime="+ PostDateTime;//数据参数队列 
  Encoding encoding = Encoding.UTF8;
   byte[] data = encoding.GetBytes(strQuery);
   
   // 准备请求...
   HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(WebSite);
   myRequest.Method = "POST";
   myRequest.ContentType="application/x-www-form-urlencoded";
   myRequest.ContentLength = data.Length;
   Stream newStream=myRequest.GetRequestStream();
   // 发送数据
   newStream.Write(data,0,data.Length);
   newStream.Close();
   
   Page.RegisterStartupScript("script",GetShowAlert("发表成功!","window.location.href('ClientPostNote.aspx');")); 
   }

   /// <summary>
  /// 去除HTML标记
  /// </summary>
  /// <param name="Htmlstring">包括HTML的源码 </param>
  /// <returns>已经去除后的文字</returns>
  public string NoHTML(string Htmlstring)
  {
   //删除脚本
   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);
   //删除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 类
http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpref/html/frlrfsystemnetwebrequestclasstopic.asp

如下代码以Get方式异步发送数据:
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 = "";//帖子内容
   noteinfo = "帖子内容:"
    +"\r\n   用户名:"+ UserName +"\r\n   网站:"+ SpotID +"\r\n   论坛:"+ BBS
    +"\r\n   版块:"+ Board +"\r\n   标题:"+ Title +"\r\n   内容:"+ Content
    +"\r\n   IP:"+ UserIp +"\r\n   URL:"+ PostUrl +"\r\n";

   string WebSite = "";//服务器接收页面
   WebSite = System.Configuration.ConfigurationSettings.AppSettings["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);//异步Post数据
   
   Page.RegisterStartupScript("script",GetShowAlert("发表成功!","window.location.href('AddNoteNet.aspx');")); 
  }

  public void BLLPostData(string noteinfo,string WebSite,string Parameters,string ParameterValues)
  {
   BLLPostDataDeal(noteinfo,WebSite,Parameters,ParameterValues);
  }
  /// <summary>
  /// 异步Post数据
  /// </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);
   
   //在开始异步调用时不提供回调委托
   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 = "";//日志
   try
   {
    if(WebSite!="")
    {
     string RegResult = "";//接收返回值
     RegResult = ConnectToWebSite2(WebSite,Parameters,ParameterValues);
     //int IsSuccess = -1;//接收情况
     
     if(RegResult=="Y")
     {
      //IsSuccess = 1;
      msg = DateTime.Now.ToString() + "  帖子传输成功!\r\n" + noteinfo;
      Log(msg);
     }
     else if(RegResult=="N")
     {
      //IsSuccess = 0;
      msg = DateTime.Now.ToString() + "  数据插入出现问题,传输不成功!\r\n" + noteinfo;
      Log(msg);
     }
     else if(RegResult=="F")
     {
      //IsSuccess = 2;
      msg = DateTime.Now.ToString() + "  服务器出现问题,传输不成功!\r\n" + noteinfo;
      Log(msg);
     }
    }
    else
    {
     msg = DateTime.Now.ToString() + "  未取得传输网址,不能继续进行传输!\r\n" + noteinfo;
     Log(msg);
    }
   }
   catch(Exception ex)
   {
    msg = DateTime.Now.ToString() + "  传输失败!错误如下:"+ ex.Message +"\r\n" + noteinfo;
    Log(msg);
   }
  }

   /// <summary>
  /// 用指定的参数(“;”分隔)访问指定的网址
  /// </summary>
  /// <param name="网址"></param>
  /// <param name="参数名称"></param>
  /// <param name="参数值"></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("参数或参数值没指定,请确认!");
   }
   else
   {
    string Delimeter = ";";
    string[] aryParm = Parameters.Split(Delimeter.ToCharArray());
    string[] aryParmValue = ParameterValues.Split(Delimeter.ToCharArray());

    if (aryParm.Length != aryParmValue.Length)
    {
     Log("参数的数量和参数值的数量不相等,请确认!");
    }
    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();  
   }

原文地址:https://www.cnblogs.com/huazai8204/p/764146.html