C# API 1.1 Get method returns

LeathalChicken
@LeathalChicken Britney Johnson

I want to use the following code to get data from the Twitter API. Every time I run it though it returns (401) Unauthorized. It will work if I POST instead of GET. Any help would be greatly appreciated.

  1. void getTwitterData(string URL, string query,string page, string per_page)
  2.     {
  3.         UserAccount sua = (UserAccount)Session["SessionUser"];
  4.         // oauth application keys
  5.         var oauth_token = sua.TWToken; //"insert here...";
  6.         var oauth_token_secret = sua.TWSecret; //"insert here...";
  7.         var oauth_consumer_key = ConfigurationManager.AppSettings["consumerKey3"];// = "insert here...";
  8.         var oauth_consumer_secret = ConfigurationManager.AppSettings["consumerSecret3"];// = "insert here...";
  9.  
  10.         // oauth implementation details
  11.         var oauth_version = "1.0";
  12.         var oauth_signature_method = "HMAC-SHA1";
  13.  
  14.         // unique request details
  15.         var oauth_nonce = Convert.ToBase64String(
  16.             new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
  17.         var timeSpan = DateTime.UtcNow
  18.             - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  19.         var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
  20.  
  21.         // create oauth signature
  22.         var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
  23.                         "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}&page={7}&per_page={8}";
  24.  
  25.         var baseString = string.Format(baseFormat,
  26.                                     oauth_consumer_key,
  27.                                     oauth_nonce,
  28.                                     oauth_signature_method,
  29.                                     oauth_timestamp,
  30.                                     oauth_token,
  31.                                     oauth_version,
  32.                                     Uri.EscapeDataString(query),
  33.                                     Uri.EscapeDataString(page),
  34.                                     Uri.EscapeDataString(per_page)
  35.                                     );
  36.  
  37.         baseString = string.Concat("GET&", Uri.EscapeDataString(URL), "&", Uri.EscapeDataString(baseString));
  38.  
  39.         var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
  40.                                 "&", Uri.EscapeDataString(oauth_token_secret));
  41.  
  42.         string oauth_signature;
  43.         using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
  44.         {
  45.             oauth_signature = Convert.ToBase64String(
  46.                 hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
  47.         }
  48.  
  49.         // create the request header
  50.         var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
  51.                            "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
  52.                            "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
  53.                            "oauth_version=\"{6}\"";
  54.  
  55.         var authHeader = string.Format(headerFormat,
  56.                                 Uri.EscapeDataString(oauth_nonce),
  57.                                 Uri.EscapeDataString(oauth_signature_method),
  58.                                 Uri.EscapeDataString(oauth_timestamp),
  59.                                 Uri.EscapeDataString(oauth_consumer_key),
  60.                                 Uri.EscapeDataString(oauth_token),
  61.                                 Uri.EscapeDataString(oauth_signature),
  62.                                 Uri.EscapeDataString(oauth_version)
  63.                         );
  64.  
  65.  
  66.         myDiv.InnerHtml = baseString + "<br/><br/><br/>" + authHeader;
  67.         //return;
  68.         ServicePointManager.Expect100Continue = false;
  69.  
  70.         // make the request
  71.         URL = URL + "?q=" + Uri.EscapeDataString(query) + "&page=" + Uri.EscapeDataString(page)+"&per_page=" + Uri.EscapeDataString(per_page);//
  72.  
  73.         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
  74.         request.Headers.Add("Authorization", authHeader);
  75.         request.Method = "GET";
  76.         request.ContentType = "application/x-www-form-urlencoded";
  77.  
  78.         WebResponse response = request.GetResponse();
  79.         var reader = new StreamReader(response.GetResponseStream());
  80.         var objText = reader.ReadToEnd();
  81.         myDiv.InnerHtml = objText;
  82.     }
1 year 8 weeks ago

Replies

LeathalChicken
@LeathalChicken Britney Johnson

Any one know what I am doing wrong?

1 year 8 weeks ago
LeathalChicken
@LeathalChicken Britney Johnson

I figured it out I took out the page and per_page on the query string and it works now just in case someone needs the same code here it is I used:

  1.         string query = "Britney " + "Johnson";
  2.         string url = "https://api.twitter.com/1.1/users/search.json";
  3.         findUserTwitter(url, query);

To call the twitter api 1.1

  1. void findUserTwitter(string resource_url, string q)
  2.     {
  3.         UserAccount sua = (UserAccount)Session["SessionUser"];
  4.         // oauth application keys
  5.         var oauth_token = sua.TWToken; //"insert here...";
  6.         var oauth_token_secret = sua.TWSecret; //"insert here...";
  7.         var oauth_consumer_key = ConfigurationManager.AppSettings["consumerKey3"];// = "insert here...";
  8.         var oauth_consumer_secret = ConfigurationManager.AppSettings["consumerSecret3"];// = "insert here...";
  9.  
  10.         // oauth implementation details
  11.         var oauth_version = "1.0";
  12.         var oauth_signature_method = "HMAC-SHA1";
  13.  
  14.         // unique request details
  15.         var oauth_nonce = Convert.ToBase64String(
  16.             new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
  17.         var timeSpan = DateTime.UtcNow
  18.             - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  19.         var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
  20.  
  21.  
  22.         // create oauth signature
  23.         var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
  24.                         "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";
  25.  
  26.         var baseString = string.Format(baseFormat,
  27.                                     oauth_consumer_key,
  28.                                     oauth_nonce,
  29.                                     oauth_signature_method,
  30.                                     oauth_timestamp,
  31.                                     oauth_token,
  32.                                     oauth_version,
  33.                                     Uri.EscapeDataString(q)
  34.                                     );
  35.  
  36.         baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
  37.  
  38.         var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
  39.                                 "&", Uri.EscapeDataString(oauth_token_secret));
  40.  
  41.         string oauth_signature;
  42.         using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
  43.         {
  44.             oauth_signature = Convert.ToBase64String(
  45.                 hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
  46.         }
  47.  
  48.         // create the request header
  49.         var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
  50.                            "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
  51.                            "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
  52.                            "oauth_version=\"{6}\"";
  53.  
  54.         var authHeader = string.Format(headerFormat,
  55.                                 Uri.EscapeDataString(oauth_nonce),
  56.                                 Uri.EscapeDataString(oauth_signature_method),
  57.                                 Uri.EscapeDataString(oauth_timestamp),
  58.                                 Uri.EscapeDataString(oauth_consumer_key),
  59.                                 Uri.EscapeDataString(oauth_token),
  60.                                 Uri.EscapeDataString(oauth_signature),
  61.                                 Uri.EscapeDataString(oauth_version)
  62.                         );
  63.  
  64.  
  65.  
  66.         ServicePointManager.Expect100Continue = false;
  67.  
  68.         // make the request
  69.         var postBody = "q=" + Uri.EscapeDataString(q);//
  70.         resource_url += "?"+postBody;
  71.         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
  72.         request.Headers.Add("Authorization", authHeader);
  73.         request.Method = "GET";
  74.         request.ContentType = "application/x-www-form-urlencoded";
  75.         var response = (HttpWebResponse)request.GetResponse();
  76.         var reader = new StreamReader(response.GetResponseStream());
  77.         var objText = reader.ReadToEnd();
  78.         myDiv.InnerHtml = objText;/**/
  79.         string html="";
  80.         try
  81.         {
  82.             JArray jsonDat = JArray.Parse(objText);
  83.             for (int x = 0; x < jsonDat.Count(); x++)
  84.             {
  85.                 html += jsonDat[x]["id"].ToString() + "<br/>";
  86.  
  87.             }
  88.             myDiv.InnerHtml = html;
  89.         }
  90.         catch (Exception twit_error)
  91.         {
  92.             myDiv.InnerHtml = html + twit_error.ToString();
  93.         }
  94.     }

I have a div on the frount page.

  1. <div runat="server" id="myDiv">
  2.     </div>

This div displays all the ids of the users I am searching for on twitter.

1 year 8 weeks ago
davidkelly1980
@davidkelly1980 David Kelly

Hi Britney
thanks for posting this code, it has helped me out a lot. one question though, line 77, reader.ReadToEnd(), how long will this reader stay open for? will it stay open for the length of time specified in oauth_timestamp or for the length of time it take to return information for your query string?
using your query string i wouldn’t expect it to take to long to pull back all the information for your name. however, I am finding for line 77 my application just hangs.

1 year 5 weeks ago
LeathalChicken
@LeathalChicken Britney Johnson

What information are you trying to pull? can you give me an example so I can try it.

1 year 5 weeks ago
davidkelly1980
@davidkelly1980 David Kelly

Hi Britney, i just realised i am trying to use the twitter userstream api not the search api which you are using.
i was able to get the search api working with the example you have but not the userstream api. Would you have any experience using this userstream api? i have followed you example code everything look good, but just having that problem i mentioned

David

1 year 5 weeks ago
LeathalChicken
@LeathalChicken Britney Johnson

try this

  1. string objText = "c";
  2.         string objText2 = "";
  3.         while (objText!="")//;//.Read();//.ReadToEnd();
  4.         {
  5.             objText = "";
  6.             try
  7.             {
  8.                 objText = reader.ReadLine();
  9.                 objText2 += " " + objText2;
  10.                 html += objText + "<br/>";
  11.                 myDiv.InnerHtml = html;/**/
  12.                 //string html = "";
  13.             }
  14.             catch (Exception er)
  15.             {
  16.                 myDiv.InnerHtml = html + "er:" + er.ToString() + "<br/>";
  17.             }
  18.  
  19.         }
  20.         try
  21.         {
  22.             JArray jsonDat = JArray.Parse(objText2);
  23.             for (int x = 0; x < jsonDat.Count(); x++)
  24.             {
  25.                 html += jsonDat[x]["id"].ToString() + "<br/>";
  26.             }
  27.             myDiv.InnerHtml = html;
  28.         }
  29.         catch (Exception twit_error)
  30.         {
  31.             myDiv.InnerHtml = html + twit_error.ToString() + "<br/>";
  32.         }
1 year 5 weeks ago
magicv0ice
@magicv0ice Vilasack Phothisan

I am getting the same unauthorized like most people. After reading this, it is probably with my signature. I am trying to do a query using the geocode. here is my code:

  1.     var geocode = "42.791306,-86.033448,1mi";
  2.             var baseFormat = "geocode={7}&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
  3.                             "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";
  4.  
  5.             var baseString = string.Format(baseFormat,
  6.                                         oauth_consumer_key,
  7.                                         oauth_nonce,
  8.                                         oauth_signature_method,
  9.                                         oauth_timestamp,
  10.                                         oauth_token,
  11.                                         oauth_version,
  12.                                         Uri.EscapeDataString(q),
  13.                                         Uri.EscapeDataString(geocode)
  14.                                         );

.....

  1. var postBody = "q=" + Uri.EscapeDataString(q) + "&geocode=" + Uri.EscapeDataString(geocode);
  2.             resource_url += "?" + postBody; 
30 weeks 1 day ago
Tariq_Ah_Man
@Tariq_Ah_Man Tariq Mansour

Any one who can answer this ? cause I'm having the same problem
thanks in advance

4 weeks 1 day ago
MNasim70
@MNasim70 Md Nasimul Haque

Thanks for posting this valuable code Britney.

5 weeks 1 day ago
ahmad_psut
@ahmad_psut ahmad

hi am sorry i dont have any solution for you but i need your help , because i think that you can help in my project so if you please give me your email , and this is my email
ahmadkamal1991_psut@hotmail.com am studying CS and i also working on my graduation project :D

1 year 8 weeks ago
JamesEFairchild
@JamesEFairchild James Fairchild

Thanks for posting this code! It worked for me, so I will meet the March 5th Twitter 1.1 API deadline. Yeah!
Make sure you change "&q=" on lines 24 & 69 of the corrected code if you are doing something other than a search for user id's.

1 year 7 weeks ago
LailaAlshahed
@LailaAlshahed Laila Alshahed

Thanks a lot for the code. The code is working with me. But Can I ask how can I manage it to work if I'm using a long or int value like "&id=" in the request "https://api.twitter.com/1.1/statuses/show.json?id=210462857140252672"?. I keep getting '401 Unauthorized'. If I use a string like looking for username or anything similar, it works perfectly but with id it does not work with me and I think I'm missing something. Can you help me with that?

1 year 7 weeks ago
LeathalChicken
@LeathalChicken Britney Johnson

on line 24 and 69 are you changing "q=" to "id="
If not go to the oauth tool and see how they make there base string
for example I was working on doing a search on twitter and was trying to add a count but I was getting 401 until I put count at the beginning.
my base string

  1.  
  2. count=100&oauth_consumer_key={0}&oauth_nonce={1}
  3. &oauth_signature_method={2}" +
  4. "&oauth_timestamp={3}&oauth_token={4}
  5. &oauth_version={5}&q={6}&result_type=mixed

twitter base string

  1. GET&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fsearch%2Ftweets.json
  2. &count%3D100
  3. ......oauth tokens.........
  4. %26q%3Dobama%26result_type%3Dmixed%26until%3D2013-03-02

You have to put everything in the right order or it will send back 401.
I hope that helps. :)

1 year 7 weeks ago
LailaAlshahed
@LailaAlshahed Laila Alshahed

Wow, that finally worked with me :) I changed the base string as you said and put the id at first. Thanks a lot for your help, don't know how to thank you enough for that. Thank you so much :)

1 year 6 weeks ago
MattHunter35
@MattHunter35 Matt Hunter

This. Thank you. You just prevented a suicide.

42 weeks 22 hours ago
sabarimd
@sabarimd Sabari M D

Thanks a Lotttttttttttttttttttttttttt Leathal Chicken...............my Hat's of to you..................You saved my day.........................

38 weeks 5 days ago
JackMarchetti
@JackMarchetti Jack Marchetti

Curious. I see you created the basestring, but it's never used when you make the actual call to Twitter.

What's the point of creating the basestring?

1 year 3 weeks ago
LeathalChicken
@LeathalChicken Britney Johnson

You use the base string to create the oauth_signature. Then the oauth_signature is used in the authHeader. Which is used to authorize your call to twitter. :)

1 year 3 weeks ago
JackMarchetti
@JackMarchetti Jack Marchetti

Thanks. I saw that after I had asked :). Unfortunately this doesn't work for me. The signature created using this method is always different than the signature I see on the "oAuth Tool" even when I use the same nonce and timestamp from the oAuth Tool.

I always get a 401 Unauthorized.

1 year 2 weeks ago
heyadamhey
@heyadamhey Adam Hey

I also get 401 unauthorised. Can you share how you got around it?

45 weeks 10 hours ago
LeathalChicken
@LeathalChicken Britney Johnson

What page of the api are you trying to get info from like GET statuses/user_timeline?

44 weeks 2 days ago
himanshuchand12
@himanshuchand12 himanshuchandra

please can anyone help me in how to finding the remaining rate limit????

49 weeks 5 days ago
HeijdenvdR
@HeijdenvdR Robert vd Heijden

thanx great help you can add the count
String baseFormat = "count=25&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";

resource_url += "?" +postBody +"&count=25" ;

45 weeks 2 days ago
rakeshpp90
@rakeshpp90 Rakesh Patil

Thanks LeathalChicken for posting this Code... ..

45 weeks 1 day ago
davidsheardown
@davidsheardown Dav.id

Wow.. thanks so much.. was trying to use other libraries, however this is the most straight forward approach given the twitter API is just REST.. however +1 for the comments above about the "correct order" of the header! really gave me some hassles initially as I wanted to get a users timeline via https://api.twitter.com/1.1/statuses/user_timeline.json and had to add the user name/screen name and count.

45 weeks 1 day ago
LeathalChicken
@LeathalChicken Britney Johnson

change line 22
"count{7}&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}";
 
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
Uri.EscapeDataString(screen_name),
Uri.EscapeDataString(count)
);

44 weeks 2 days ago
nithish07
@nithish07 Nithish Ravindran

please tell me what u mean by UserAccount sua = (UserAccount)Session["SessionUser"];

44 weeks 4 days ago
LeathalChicken
@LeathalChicken Britney Johnson

That is a variable that I have in my code that creates a way for me to keep track of both the users twitter account data and Facebook data you don't need to use it.

44 weeks 2 days ago
tarunichitturi
@tarunichitturi tarunichitturi

its working fine,but when i tried with show.json instead of search.json iam getting 401 unauthorized error,can u please suggest me how to do with show.json by passing screen_name

44 weeks 1 day ago
LeathalChicken
@LeathalChicken Britney Johnson

change the q to screen_name

44 weeks 1 day ago
yugamanand
@yugamanand yugam anand

Hi @LeathalChicken

Can you please help me....in

I am able to get error : :"The remote server returned an error: (401) Unauthorized."

When trying for Get Search Tweet method
Base Format that i generate
count={0}&max_id={1}&oauth_consumer_key={2}&oauth_nonce={3}&oauth_signature_method={4}&oauth_timestamp={5}&oauth_token={6}&oauth_version={7}&q={8}&result_type={9}&since_id={10}

Header format
OAuth oauth_consumer_key="{0}", oauth_nonce="{1}", oauth_signature="{2}", oauth_signature_method="{3}", oauth_timestamp="{4}", oauth_token="{5}", oauth_version="{6}"

url
https://api.twitter.com/1.1/search/tweets.json?count=4&max_id=250126199840518145&q=%40yugamanand&result_type=mixed&since_id=24012619984051000

44 weeks 1 day ago
LeathalChicken
@LeathalChicken Britney Johnson

everything looks fine here are you using the Uri.EscapeDataString() you may have a caricter that can not be in the url try searching for a username with out the @

44 weeks 1 day ago
yugamanand
@yugamanand yugam anand

Hi

I m getting error : "The remote server returned an error: (401) Unauthorized."

url for get tweet : https://api.twitter.com/1.1/search/tweets.json

For Get Tweet search method but able to authenticate using get user_timeline

44 weeks 1 day ago
jansonluan
@jansonluan Janson L.

I'm able to make the specific user statuses work based on your example, but when I'm trying to make another call for:

https://api.twitter.com/1.1/lists/statuses.json

GET: https://api.twitter.com/1.1/lists/statuses.json?id=91500933

it's not working. Any advice would be great. Here's how I've formatted my the header, and oauth signature from base.

  1.         var baseFormat = "id={8}&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
  2.                         "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";
  3.  
  4.         var baseString = string.Format(baseFormat,
  5.                                     oauth_consumer_key,
  6.                                     oauth_nonce,
  7.                                     oauth_signature_method,
  8.                                     oauth_timestamp,
  9.                                     oauth_token,
  10.                                     oauth_version,
  11.                                      Uri.EscapeDataString(screen_name),
  12.                                      Uri.EscapeDataString(count),
  13.                                      Uri.EscapeDataString(id)
  14.                                     );
  15.  
  16.         var headerFormat = "Authorization: OAuth oauth_consumer_key=\"{3}\", oauth_nonce=\"{0}\", oauth_signature=\"{5}\", oauth_signature_method=\"{1}\", oauth_timestamp=\"{2}\", oauth_token=\"{4}\", oauth_version=\"{6}\"";
  17.  
  18.         var authHeader = string.Format(headerFormat,
  19.                                 Uri.EscapeDataString(oauth_nonce),
  20.                                 Uri.EscapeDataString(oauth_signature_method),
  21.                                 Uri.EscapeDataString(oauth_timestamp),
  22.                                 Uri.EscapeDataString(oauth_consumer_key),
  23.                                 Uri.EscapeDataString(oauth_token),
  24.                                 Uri.EscapeDataString(oauth_signature),
  25.                                 Uri.EscapeDataString(oauth_version)

I'm receiving a 400 Bad Request

Any ideas?

44 weeks 1 day ago
LeathalChicken
@LeathalChicken Britney Johnson

You're using GET lists/statuses and their is no variable named id.

Parameters

Either a list_id or a slug is required. If providing a list_slug, an owner_screen_name or owner_id is also required.

list_id required
The numerical id of the list.

slug required
You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters.

owner_screen_name optional
The screen name of the user who owns the list being requested by a slug.

owner_id optional
The user ID of the user who owns the list being requested by a slug.

since_id optional
Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available.

max_id optional
Returns results with an ID less than (that is, older than) or equal to the specified ID.

count optional
Specifies the number of results to retrieve per "page."

include_entities optional
Entities are ON by default in API 1.1, each tweet includes a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. You can omit entities from the result by using include_entities=false

include_rts optional
When set to either true, t or 1, the list timeline will contain native retweets (if they exist) in addition to the standard stream of tweets. The output format of retweeted tweets is identical to the representation you see in home_timeline.

43 weeks 5 days ago
hasaphoto
@hasaphoto Hamid Salehian

To get tweets you only need change the url to https://api.twitter.com/1.1/statuses/user_timeline.json and change the id to text like this jsonDat[x]["text"].ToString()

43 weeks 6 days ago
bsendev
@bsendev bsendev

Thanks so much for this post! It saved my day :-)

44 weeks 13 hours ago
JoshuaGrippo
@JoshuaGrippo Joshua Grippo

This post was really helpful. I finally broke down and read all of https://dev.twitter.com/docs/auth/creating-signature to understand what was happening with the parameters and the auth string

I modifed the awesome code from @LethalChicken

  1. public static string MakeTwitterCall(string resource_url, IEnumerable<KeyValuePair<string, string>> RequestParameters)
  2.     {
  3.         // oauth application keys
  4.         var oauth_token = "----";
  5.         var oauth_token_secret = "-----";
  6.         var oauth_consumer_key = "-----";
  7.         var oauth_consumer_secret = "-----";
  8.  
  9.         // oauth implementation details
  10.         var oauth_version = "1.0";
  11.         var oauth_signature_method = "HMAC-SHA1";
  12.  
  13.         // unique request details
  14.         var oauth_nonce = Convert.ToBase64String(
  15.             new System.Text.ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
  16.         var timeSpan = DateTime.UtcNow
  17.             - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  18.         var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
  19.  
  20.         //setup the parameters that we will be putting in the authorization
  21.         var authorizationParameters = new List<KeyValuePair<string, string>>() { 
  22.                 new KeyValuePair<string, string>("oauth_consumer_key",oauth_consumer_key),
  23.                 new KeyValuePair<string, string>("oauth_nonce",oauth_nonce),
  24.                 new KeyValuePair<string, string>("oauth_signature_method",oauth_signature_method),
  25.                 new KeyValuePair<string, string>("oauth_timestamp",oauth_timestamp),
  26.                 new KeyValuePair<string, string>("oauth_token",oauth_token),
  27.                 new KeyValuePair<string, string>("oauth_version",oauth_version)
  28.         };
  29.  
  30.         //combine and sort all parameters as per https://dev.twitter.com/docs/auth/creating-signature
  31.         var allParameters = authorizationParameters.Union(RequestParameters).OrderBy(tmp => tmp.Key);
  32.  
  33.         //put all paramneters into a & delimited string and make sure our values are % escaped        
  34.         var baseString = string.Join("&", allParameters.Select(p => string.Format("{0}={1}", p.Key, Uri.EscapeDataString(p.Value))));
  35.         //finish the base string
  36.         baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
  37.  
  38.         var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
  39.                                 "&", Uri.EscapeDataString(oauth_token_secret));
  40.  
  41.         //use our composite key to get the auth signature
  42.         string oauth_signature=null;
  43.         using (System.Security.Cryptography.HMACSHA1 hasher = new System.Security.Cryptography.HMACSHA1(System.Text.ASCIIEncoding.ASCII.GetBytes(compositeKey)))
  44.         {
  45.             oauth_signature = Convert.ToBase64String(
  46.                 hasher.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(baseString)));
  47.         }
  48.  
  49.         // create the request header
  50.         var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
  51.                            "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
  52.                            "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
  53.                            "oauth_version=\"{6}\"";
  54.  
  55.         //get the actual string version of the auth header and its values
  56.         var authHeader = string.Format(headerFormat,
  57.                                 Uri.EscapeDataString(oauth_nonce),
  58.                                 Uri.EscapeDataString(oauth_signature_method),
  59.                                 Uri.EscapeDataString(oauth_timestamp),
  60.                                 Uri.EscapeDataString(oauth_consumer_key),
  61.                                 Uri.EscapeDataString(oauth_token),
  62.                                 Uri.EscapeDataString(oauth_signature),
  63.                                 Uri.EscapeDataString(oauth_version)
  64.                         );
  65.  
  66.  
  67.  
  68.         System.Net.ServicePointManager.Expect100Continue = false;
  69.  
  70.         //add our query string parameters to our url
  71.         resource_url += "?" + string.Join("&", RequestParameters.Select(p => string.Format("{0}={1}", p.Key, Uri.EscapeDataString(p.Value))));
  72.  
  73.         //create our request
  74.         System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(resource_url);
  75.  
  76.         //set our info
  77.         request.Headers.Add("Authorization", authHeader);
  78.         request.Method = "GET";
  79.         request.ContentType = "application/x-www-form-urlencoded";
  80.  
  81.         //get the response and return the result from the stream
  82.         using (var response = (System.Net.HttpWebResponse)request.GetResponse())
  83.         {
  84.             using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
  85.             {
  86.                 return reader.ReadToEnd();                
  87.             }
  88.         }
  89.     }
43 weeks 2 days ago
tsearchhero
@tsearchhero Search Hero

Hi Joshua,

code works perfect. But, how can I add geocode and unti parameters to your MakeTwitterCall function. These parameters are listed in this url: https://dev.twitter.com/docs/api/1.1/get/search/tweets

Many of these are working but when I add these two parameters in my IEnumerable<KeyValuePair<string, string>> RequestParameters then twitter send empty results.

Can you help me?
Thanks.

7 weeks 3 days ago
cadmagician
@cadmagician Koós Zoltán

nice, but how is it works with POST? eg status update? thanks.

43 weeks 3 days ago
PatrickBadine
@PatrickBadine Patrick Badine

im trying to get tweets by their twitter id, is that possible using this?

43 weeks 2 days ago
globesnews
@globesnews globesnews

yes, u can use user_id instead of screen_name

43 weeks 1 day ago
JoshuaGrippo
@JoshuaGrippo Joshua Grippo
  1.             TwitterHelper.MakeTwitterCall(
  2.                 "https://api.twitter.com/1.1/statuses/user_timeline.json",
  3.                 new KeyValuePair<string, string>[] {
  4.                     new KeyValuePair<String, String>("screen_name","joshuagrippo"),
  5.                     new KeyValuePair<String, String>("count", "3")
  6.             });
  1.             TwitterHelper.MakeTwitterCall(
  2.                 "https://api.twitter.com/1.1/statuses/user_timeline.json",
  3.                 new KeyValuePair<string, string>[] {
  4.                     new KeyValuePair<String, String>("user_id","634067507"),
  5.                     new KeyValuePair<String, String>("count", "3")
  6.             });
43 weeks 2 days ago
JoshuaGrippo
@JoshuaGrippo Joshua Grippo

OK, let's try this again without my secret keys :)

Your application permissions need to be at least read write. I had to recreate then reset my keys before it would take effect.

the code below assumes you have your keys stored in your app/web config. you can do what yoou like as far as encryption.

  1.  public static class TwitterHelper
  2.     {
  3.         private static string TwitterCall(string Method, string ResourceUrl, IEnumerable<KeyValuePair<string, string>> RequestParameters)
  4.         {           
  5.             // oauth application keys
  6.             var oauth_token = System.Configuration.ConfigurationManager.AppSettings["twitterAccessToken"];
  7.             var oauth_token_secret = System.Configuration.ConfigurationManager.AppSettings["twitterAccessTokenSecret"];
  8.             var oauth_consumer_key = System.Configuration.ConfigurationManager.AppSettings["twitterConsumerKey"];
  9.             var oauth_consumer_secret = System.Configuration.ConfigurationManager.AppSettings["twitterConsumerSecret"];
  10.  
  11.             // oauth implementation details
  12.             var oauth_version = System.Configuration.ConfigurationManager.AppSettings["twitterOAuthVersion"];
  13.             var oauth_signature_method = System.Configuration.ConfigurationManager.AppSettings["twitterOAuthSignatureMethod"];
  14.  
  15.             // unique request details
  16.             var oauth_nonce = Convert.ToBase64String(
  17.                 new System.Text.ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
  18.             var timeSpan = DateTime.UtcNow
  19.                 - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  20.             var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
  21.  
  22.             //setup the parameters that we will be putting in the authorization
  23.             var authorizationParameters = new List<KeyValuePair<string, string>>() { 
  24.                 new KeyValuePair<string, string>("oauth_consumer_key",oauth_consumer_key),
  25.                 new KeyValuePair<string, string>("oauth_nonce",oauth_nonce),
  26.                 new KeyValuePair<string, string>("oauth_signature_method",oauth_signature_method),
  27.                 new KeyValuePair<string, string>("oauth_timestamp",oauth_timestamp),
  28.                 new KeyValuePair<string, string>("oauth_token",oauth_token),
  29.                 new KeyValuePair<string, string>("oauth_version",oauth_version)
  30.             };
  31.  
  32.             //combine and sort all parameters as per https://dev.twitter.com/docs/auth/creating-signature
  33.             var allParameters = authorizationParameters.Union(RequestParameters).OrderBy(tmp => tmp.Key);
  34.  
  35.             //put all paramneters into a & delimited string and make sure our values are % escaped        
  36.             var baseString = string.Join("&", allParameters.Select(p => string.Format("{0}={1}", p.Key, Uri.EscapeDataString(p.Value))));
  37.  
  38.             //finish the base string
  39.             baseString = string.Format("{0}&{1}&{2}", Method, Uri.EscapeDataString(ResourceUrl), Uri.EscapeDataString(baseString));
  40.  
  41.             var compositeKey = string.Format("{0}&{1}",Uri.EscapeDataString(oauth_consumer_secret),Uri.EscapeDataString(oauth_token_secret));
  42.  
  43.             //use our composite key to get the auth signature
  44.             string oauth_signature = null;
  45.             using (System.Security.Cryptography.HMACSHA1 hasher = new System.Security.Cryptography.HMACSHA1(System.Text.ASCIIEncoding.ASCII.GetBytes(compositeKey)))
  46.             {
  47.                 oauth_signature = Convert.ToBase64String(
  48.                     hasher.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(baseString)));
  49.             }
  50.  
  51.             // create the request header
  52.             var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
  53.                                "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
  54.                                "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
  55.                                "oauth_version=\"{6}\"";
  56.  
  57.             //get the actual string version of the auth header and its values
  58.             var authHeader = string.Format(headerFormat,
  59.                                     Uri.EscapeDataString(oauth_nonce),
  60.                                     Uri.EscapeDataString(oauth_signature_method),
  61.                                     Uri.EscapeDataString(oauth_timestamp),
  62.                                     Uri.EscapeDataString(oauth_consumer_key),
  63.                                     Uri.EscapeDataString(oauth_token),
  64.                                     Uri.EscapeDataString(oauth_signature),
  65.                                     Uri.EscapeDataString(oauth_version)
  66.                             );
  67.  
  68.  
  69.  
  70.             System.Net.ServicePointManager.Expect100Continue = false;
  71.  
  72.             //add our query string parameters to our url
  73.             var parameterString = string.Join("&", RequestParameters.Select(p => string.Format("{0}={1}", p.Key, Uri.EscapeDataString(p.Value))));
  74.             ResourceUrl += "?" + parameterString;
  75.  
  76.  
  77.             //create our request
  78.             System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ResourceUrl);
  79.  
  80.             //set our info
  81.             request.Headers.Add("Authorization", authHeader);
  82.             request.Method = Method;
  83.             request.ContentType = "application/x-www-form-urlencoded";
  84.  
  85.             //get the response and return the result from the stream
  86.             using (var response = (System.Net.HttpWebResponse)request.GetResponse())
  87.             {
  88.                 using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
  89.                 {
  90.                     return reader.ReadToEnd();
  91.                 }
  92.             }
  93.         }
  94.  
  95.         public static string TwitterCallGet(string ResourceUrl, IEnumerable<KeyValuePair<string, string>> RequestParameters)
  96.         {
  97.             return TwitterCall("GET", ResourceUrl, RequestParameters);
  98.         }
  99.  
  100.         public static string TwitterCallPost(string ResourceUrl, IEnumerable<KeyValuePair<string, string>> RequestParameters)
  101.         {
  102.             return TwitterCall("POST", ResourceUrl, RequestParameters);
  103.         }
  104.     }
43 weeks 1 day ago
theSeanCook
@theSeanCook Sean Cook

Thanks for sharing your code, Joshua.

43 weeks 1 day ago
anur8g
@anur8g Anurag

Thank you @JoshuaGrippo, your code works. it saved my day. :) Thakn you

25 weeks 5 days ago
cgoasduff
@cgoasduff christophe Goasduff

Thanks a lot Britney.. you rock!

42 weeks 5 days ago
LeathalChicken
@LeathalChicken Britney Johnson

Ah! Thank you I feel warm and fuzzys. :)

42 weeks 5 days ago
developingtwit
@developingtwit JVillasmil

Very useful code to get the tweet search done! Thanks @leathalchicken

42 weeks 5 days ago
kirkhofer
@kirkhofer Kirk Hofer

Just converted to PowerShell and it works like a champ! Good stuff...

42 weeks 2 days ago