Web Design that taps into the haromny and vision of your dreams.

Posting Form Data to Remote Site using HttpWebRequest

How to send data to remove web servers with C#

Written By on in Coding

194 words, estimated reading time 1 minutes.

Using this snippet of code you can easily send data using HttpWebRequest Post. The data is sent via the HTTP POST method to a remote server from your code behind.

This global code snippet for using HttpWebRequest Post can be used from a code behind web form, console application or Windows form application.

string oid = "364826B3-7D29-4C2E-9568-C318C2B45F0C";
string retURL = CurrentPage.Url;
string remoteUrl = https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8";
string name = Request.Form["name"];
string email = Request.Form["email"];
 
// Setup the POST data
string poststring = String.Format("oid={0}&retURL={1}&name={2}&email={3}", oid, retURL, name, email);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(remoteUrl);
 
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
 
// Convert the post string to a byte array
byte[] bytedata = System.Text.Encoding.UTF8.GetBytes(poststring);
httpRequest.ContentLength = bytedata.Length;
 
// Create the stream
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
 
// Get the response from remote server
HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
 
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        sb.Append(line);
    }
}
 
string serverResponse = sb.ToString();

Last updated on: Tuesday 20th June 2017

 

Comments

There are no comments for this post. Be the first!

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

 

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me