Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remote HTTP Post with C# [duplicate]

Tags:

c#

webrequest

How do you do a Remote HTTP Post (request) in C#?

like image 761
localhost Avatar asked Nov 29 '22 20:11

localhost


1 Answers

This is code from a small app I wrote once to post a form with values to a URL. It should be pretty robust.

_formValues is a Dictionary<string,string> containing the variables to post and their values.


// encode form data
StringBuilder postString = new StringBuilder();
bool first=true;
foreach (KeyValuePair pair in _formValues)
{
    if(first)
        first=false;
    else
        postString.Append("&");
    postString.AppendFormat("{0}={1}", pair.Key, System.Web.HttpUtility.UrlEncode(pair.Value));
}
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postString.ToString());

// set up request object
HttpWebRequest request;
try
{
    request = WebRequest.Create(url) as HttpWebRequest;
}
catch (UriFormatException)
{
    request = null;
}
if (request == null)
    throw new ApplicationException("Invalid URL: " + url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;

// add post data to request
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

like image 74
David Avatar answered Dec 09 '22 19:12

David