POSTing Data with ASP.NET
ASPAlliance.com: The #1 ASP.NET Community
The ASPSmith
Search
D: | Domains | Authors.aspalliance.com | Stevesmith | Articles | POSTing Data with ASP.NET
POSTing Data with ASP.NET

By Steven Smith

[Example/C#]
[Example/VB]

Thanks to Alex Lowe for this updated code. Using the example code listed below, you can easily convert the page scraping code described in the last article to use the POST protocol. This will allow you to submit form information to sites and retrieve the results, which allows for great interop opportunities. We covered the basics of this technique in the last article, so now I'm just going to demonstrate the code.

/stevesmith/articles/examples/cs/postscrape.aspx

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<script language="C#" runat="server">
   void Page_Load(Object Src, EventArgs E) {
      myPage.Text = readHtmlPage("http://aspalliance.com/aldotnet/examples/posttest.asp");
   }

   private String readHtmlPage(string url)
   {
      String result = "";
      String strPost = "x=1&y=2&z=YouPostedOk";
      StreamWriter myWriter = null;
      
      HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
      objRequest.Method = "POST";
      objRequest.ContentLength = strPost.Length;
      objRequest.ContentType = "application/x-www-form-urlencoded";
      
      try
      {
         myWriter = new StreamWriter(objRequest.GetRequestStream());
         myWriter.Write(strPost);
      }
      catch (Exception e)
      {
         return e.Message;
      }
      finally {
         myWriter.Close();
      }
         
      HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
      using (StreamReader sr =
         new StreamReader(objResponse.GetResponseStream()) )
      {
         result = sr.ReadToEnd();

         // Close and clean up the StreamReader
         sr.Close();
      }
      return result;
   }   
</script>
<html>
<body>
<b>This content is being populated from a separate HTTP request to
<a href="http://aspalliance.com/aldotnet/examples/posttest.asp">
http://aspalliance.com/aldotnet/examples/posttest.asp</a>:</b><hr/>
<asp:literal id="myPage" runat="server"/>
</body>
</html>
C# VB JScript

Related Articles:




ASP.NET Developer's Cookbook, By Steven Smith, Rob Howard, ASPAlliance.com 

ASP.NET By Example, By Steven Smith 




Steven Smith, MCSE + Internet (4.0)
Last Modified: 8/6/2001 10:36:29 AM
History: 1/25/2004 7:10:06 PM