Wednesday, November 21, 2007

How to collect post data and then send it to a remote url as a post using Asp.NET.

Collect post data and send to remote URL as post. I know there is a postbackurl property that can be used, but this method allows you to modify, add, and remove from what you send to the new URL as a post. I've used this technique when integrating with PayPal and I needed to dynamically create a product that is being purchased (by including their user information), but this has many purposed.

void PostMe1(Object sender,EventArgs e){

RemotePost myremotepost = new RemotePost();

myremotepost.Url = "http://www.jigar.net/demo/HttpRequestDemoServer.aspx";

myremotepost.Add("field1","Tom");

myremotepost.Add("field2","Sawyer");

myremotepost.Post();

}

void PostMe2(Object sender,EventArgs e){

RemotePost myremotepost = new RemotePost();

myremotepost.Url = "http://www.jigar.net/demo/HttpRequestDemoServer.aspx";

myremotepost.Add("field1","Huckleberry");

myremotepost.Add("field2","Finn");

myremotepost.Post();

}


public class RemotePost{

private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();


public string Url = "";

public string Method = "post";

public string FormName = "form1";



public void Add(string name,string value){

Inputs.Add(name,value);

}



public void Post(){

System.Web.HttpContext.Current.Response.Clear();


System.Web.HttpContext.Current.Response.Write("<html><head>");



System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload="\">",FormName));

System.Web.HttpContext.Current.Response.Write(string.Format("<form name="\" method="\" action="\">",FormName,Method,Url));

for(int i=0;i< Inputs.Keys.Count;i++){

System.Web.HttpContext.Current.Response.Write(string.Format("<input name="\" type="\" value="\">",Inputs.Keys[i],Inputs[Inputs.Keys[i]]));

}

System.Web.HttpContext.Current.Response.Write("</form>");

System.Web.HttpContext.Current.Response.Write("</body></html>");


System.Web.HttpContext.Current.Response.End();

}

}


0 comments: