Posting form data to remote website using HttpWebRequest.

How do I post form data to remote web application using asp.net, I want to post data in background and display result from remote server to user.

Following code will send form data to remote application , Get response and display to user.

Run sample code  

------------------
Demo Client
------------------

<%@ Page Language="C#" %>
<%@ import Namespace="System.Net" %>
<%@ import Namespace="System.IO" %>
<%@ import Namespace="System.Text" %>

<script runat="server">
void PostMe(object sender, EventArgs e){
    string poststring = String.Format("field1={0}&field2={1}",text1.Text,text2.Text);
    ResponseResult.Text = "<hr/>" +  
    GetResponseString("http://www.jigar.net/demo/HttpRequestDemoServer.aspx",poststring);
}

String GetResponseString(string url, string poststring){
    HttpWebRequest httpRequest = 
    (HttpWebRequest)WebRequest.Create("http://www.jigar.net/demo/HttpRequestDemoServer.aspx"); 
    
    httpRequest.Method = "POST"; 
    httpRequest.ContentType = "application/x-www-form-urlencoded"; 

    byte[] bytedata =  Encoding.UTF8.GetBytes(poststring);
    httpRequest.ContentLength = bytedata.Length;

    Stream requestStream = httpRequest.GetRequestStream();
    requestStream.Write(bytedata, 0, bytedata.Length);
    requestStream.Close();


    HttpWebResponse httpWebResponse = 
    (HttpWebResponse)httpRequest.GetResponse();
    Stream responseStream =  httpWebResponse.GetResponseStream();

    StringBuilder sb = new StringBuilder();

    using (StreamReader reader = 
    new StreamReader(responseStream, System.Text.Encoding.UTF8))
    {
      string line;
      while ((line = reader.ReadLine()) != null)
      {
        sb.Append(line);
      }
    }

    return sb.ToString();

}

</script>
<html>
<head>
</head>
<body>
    <form runat="Server">
        field1 : <asp:TextBox runat="Server" id="text1"/>
        <br/>
        field2 : <asp:TextBox runat="Server" id="text2"/>
        <br/>
        <asp:button runat="Server" onclick="PostMe" Text="Post"/>

        
        <asp:Literal runat="Server" id="ResponseResult" />
        
    </form>
</body>
</html>

------------------
Demo Server
------------------

<%@ Page Language="C#" %>
<script runat="server">
    void Page_Load(object sender, EventArgs e){
        if(Request.Form["field1"] != null ){
            Response.Write("field1 : " + Request.Form["field1"] + "</br>");
        }
        if(Request.Form["field2"] != null ){
            Response.Write("field2 : " +Request.Form["field2"] + "</br>");
        }
    }
</script>
Bookmark with:
Technorati   Digg   Delicious   StumbleUpon   Facebook
My name is Jigar Desai I share my ideas on this site and you can contact me by filling contact form.

Categories