Skip to content

Instantly share code, notes, and snippets.

@sandrinodimattia
Created July 23, 2012 06:19
Show Gist options
  • Save sandrinodimattia/3162254 to your computer and use it in GitHub Desktop.
Save sandrinodimattia/3162254 to your computer and use it in GitHub Desktop.
Google POST Request
/// <summary>
/// Send a post request to Google.
/// </summary>
/// <param name="url"></param>
/// <param name="postFields"></param>
/// <returns></returns>
public void PostRequest(string url, params GoogleParameter[] postFields)
{
// Format the parameters.
string formattedParameters = string.Empty;
foreach (var par in postFields.Where(o => o != null))
formattedParameters += string.Format("{0}={1}&", par.Name, par.Value);
formattedParameters = formattedParameters.TrimEnd('&');
// Append a token.
formattedParameters += String.Format("&{0}={1}", "T", GetToken());
// Get the current post data and encode.
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] encodedPostData = ascii.GetBytes(
String.Format(formattedParameters));
// Prepare request.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = encodedPostData.Length;
// Add the authentication header.
request.Headers.Add("Authorization", "GoogleLogin auth=" + auth);
// Write parameters to the request.
using (Stream newStream = request.GetRequestStream())
newStream.Write(encodedPostData, 0, encodedPostData.Length);
// Get the response and validate.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
throw new LoginFailedException(
response.StatusCode, response.StatusDescription);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment