Skip to content

Instantly share code, notes, and snippets.

@anova
Created October 27, 2015 17:56
Show Gist options
  • Save anova/6fea7f59046b4cf6c5fc to your computer and use it in GitHub Desktop.
Save anova/6fea7f59046b4cf6c5fc to your computer and use it in GitHub Desktop.
Twitter WebRequest example
//https://dev.twitter.com/oauth/application-only
//Step 1
string strBearerRequest = HttpUtility.UrlEncode(this.ConsumerKey) + ":" + HttpUtility.UrlEncode(this.ConsumerSecret);
//http://stackoverflow.com/a/11743162
strBearerRequest = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(strBearerRequest));
//Step 2
WebRequest request = WebRequest.Create("https://api.twitter.com/oauth2/token");
request.Headers.Add("Authorization", "Basic " + strBearerRequest);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
string strRequestContent = "grant_type=client_credentials";
byte[] bytearrayRequestContent = System.Text.Encoding.UTF8.GetBytes(strRequestContent);
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytearrayRequestContent, 0, bytearrayRequestContent.Length);
requestStream.Close();
string responseJson = string.Empty;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
responseJson = new StreamReader(responseStream).ReadToEnd();
}
JObject jobjectResponse = JObject.Parse(responseJson);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment