Skip to content

Instantly share code, notes, and snippets.

@nozzlegear
Last active August 29, 2015 14:09
Show Gist options
  • Save nozzlegear/d3e83c5e1fda66328b6f to your computer and use it in GitHub Desktop.
Save nozzlegear/d3e83c5e1fda66328b6f to your computer and use it in GitHub Desktop.
Join KeyValuePairs into an x-www-formurlencoded string, then POST it to a URL.
public async Task<string> YourMethod()
{
//Create a list of your parameters
var postParams = new List<KeyValuePair<string, object>>(){
new KeyValuePair<string, object>("FirstParameter", "First Value") ,
new KeyValuePair<string, object>("SecondParameter", "Second Value")
};
//Join KVPs into a x-www-formurlencoded string
var formString = string.Join("&", postParams.Select(x => string.Format("{0}={1}", x.Key, x.Value)));
//output: FirstParamter=FirstValue&SecondParamter=SecondValue
//Encode form string to bytes
var bytes = Encoding.UTF8.GetBytes(formString);
//Create a POST webrequest
var request = WebRequest.CreateHttp("https://www.example.com");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//Open request stream
using (var reqStream = await request.GetRequestStreamAsync())
{
//Write bytes to the request stream
await reqStream.WriteAsync(bytes, 0, bytes.Length);
}
//Try to get response
WebResponse response = null;
try
{
response = await request.GetResponseAsync();
}
catch (WebException e)
{
//Something went wrong with our request. Return the exception message.
return e.Message;
}
//Get response stream
using (var respStream = response.GetResponseStream())
{
//Create a streamreader to read the website's response, then return it as a string
using (var reader = new StreamReader(respStream))
{
return await reader.ReadToEndAsync();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment