I'm a newbie in C# and asp.net.
I'm trying to create a simple web(run on localhost) which use streaming and search API of Twitter.
I've tried some query like: "https://api.twitter.com/1.1/statuses/mentions_timeline.json?count=2&since_id=14927799" but it got some error about "Bad Authentication data".
May be I don't know how to get Authentication. So could anyone help me? THanks a lots.
What you have shown is not the search functionality, rather is the stream functionality.
Here is a complete example of working twitter stream search
private void SearchTweetsWithQuery(string query)
{
var oauth_token = System.Configuration.ConfigurationManager.AppSettings["accessToken"];
var oauth_token_secret = System.Configuration.ConfigurationManager.AppSettings["accessTokenSecret"];
var oauth_consumer_key = System.Configuration.ConfigurationManager.AppSettings["consumerKey"];
var oauth_consumer_secret = System.Configuration.ConfigurationManager.AppSettings["consumerSecret"];
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
// message api details
var status = "Updating status via REST API if this works";
var resource_url = "https://api.twitter.com/1.1/search/tweets.json";
var screen_name = "TODO : UPDATE THIS OR LEAVE BLANK";
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
query
);
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_consumer_key=\"{3}\", oauth_nonce=\"{0}\", oauth_signature=\"{5}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", " +
"oauth_token=\"{4}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
// make the request
ServicePointManager.Expect100Continue = false;
var postBody = "screen_name=" + Uri.EscapeDataString(screen_name);
resource_url += "?q=" + query;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
First you should create an application. https://dev.twitter.com/apps .
Then you can use Twitterizer's WebRequestBuilder class to form your request. ( http://svn.twitterizer.net/twitterizer/trunk/Twitterizer2/OAuth/ )
var tokens = new Twitterizer.OAuthTokens
{
ConsumerKey = "....",
ConsumerSecret = "....",
AccessToken = "....",
AccessTokenSecret = "......"
};
string url = "https://api.twitter.com/1.1/statuses/mentions_timeline.json?count=2&since_id=14927799";
var builder = new Twitterizer.WebRequestBuilder(new Uri(url), Twitterizer.HTTPVerb.GET, tokens);
var req = builder.PrepareRequest();
var resp = req.GetResponse();
var json = new StreamReader(resp.GetResponseStream()).ReadToEnd();
resp.Close();
Related
I am working with Twitter AccountActivity API and DM API but when it comes to POST/DELETE requests, i get this error :
401 Unauthorized
But the GET requests just work fine. I think i have something wrong with the request header. Could someone please help?
This is a sample of the code i am using :
public WebResponse PostWelcomeMessageRule(HttpWebRequest request)
{
var oauth_token = ConfigurationManager.AppSettings["TK"];
var oauth_token_secret = ConfigurationManager.AppSettings["TS"];
var oauth_consumer_key = ConfigurationManager.AppSettings["CK"].ToString();
var oauth_consumer_secret = ConfigurationManager.AppSettings["CS"].ToString();
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
var welcomeMsgId = 961185762921328645;
// unique request details
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
// message api details
var resource_url = "https://api.twitter.com/1.1/direct_messages/welcome_messages/rules/new.json";
// create oauth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&welcome_message_id={6}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
welcomeMsgId
);
baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\", welcome_message_id=\"{7}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version),
Uri.EscapeDataString(welcomeMsgId.ToString())
);
request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
WebResponse response = request.GetResponse();
string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
return response;
}
I'm trying to retrieve profile data for an authenticated twitter user using the home_timeline API call. I've got a specific method used for this purpose and at this point I'm just trying to return the JSON string to verify it works, but I'm getting a 400 error.
public string getProfile(){
// set your own keys and screen name
var oauth_consumer_key = "consumerKeyHere";
var oAuthConsumerSecret = "consumerSecretHere";
var oAuthUrl = "https://api.twitter.com/1.1/statuses/home_timeline.json";
var oauth_token_secret = "tokenSecretHere";
// Authenticate
var authHeaderFormat = "Basic {0}";
var postBody = "grant_type=client_credentials";
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
var oauth_token = token.access_token; // this token is generated by another class (token) where I retrieve the access token. Verified that authentication works.
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// create oauth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version
);
baseString = string.Concat("GET&", Uri.EscapeDataString("https://api.twitter.com/1.1/statuses/home_timeline.json"), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_key),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))) {
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", " +
"oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", " +
"oauth_timestamp=\"{4}\", oauth_token=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "GET";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
using (authResponse)
{
using (var reader = new StreamReader(authResponse.GetResponseStream())) {
String js = reader.ReadToEnd();
return js;
}
}
}
My arguments were in the wrong order for authHeader:
var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", " +
"oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", " +
"oauth_timestamp=\"{4}\", oauth_token=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
This question already has answers here:
Authenticate and request a user's timeline with Twitter API 1.1 oAuth
(2 answers)
Closed 4 years ago.
I have the following code shamelessly taken from dev.twitter to get the time line of a specific user:
string endpoint = "https://api.twitter.com/1.1/statuses/user_timeline.json";
string user_name = ".....";
string ConsumerKey = "....";
string ConsumerSecret = "........";
string Token = ".......";
string TokenSecret = "........";
// oauth application keys
var oauth_token = Token;
var oauth_token_secret = TokenSecret;
var oauth_consumer_key = ConsumerKey;
var oauth_consumer_secret = ConsumerSecret;
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
var baseFormat = "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,
user_name
);
//&include_rts=true &exclude_replies=false
baseString = string.Concat("GET&", Uri.EscapeDataString(endpoint), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
string headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\",screen_name=\"{7}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version),
Uri.EscapeDataString(user_name)
);
// make the request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var objText = reader.ReadToEnd();
However, I'm getting a 401, Unauthorized error on this line:
var response = (HttpWebResponse)request.GetResponse();
(as indeed are the last couple of posters on that Twitter developer thread).
Is there any way I can quickly check that my various tokens, keys and secrets are valid and should return the data I'm looking for?
I have created a test console application on GitHub that does this here:
Authenticate and request a user's timeline with Twitter API 1.1 oAuth
Please see my question and answer, markup if you find it of use.
I got some code for Twitter update and search api from CodeProject which worked just fine.
However, i get 401 when i tried to convert it for the stream api: "https://stream.twitter.com/1/statuses/filter.json". I will appreciate any help. See code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Security.Cryptography;
using System.IO;
public class OAuthRead
{
public static void Authenticate()
{
// oauth application keys
var oauth_consumer_key = "****";
var oauth_consumer_secret = "*****";
var oauth_token = "******";
var oauth_token_secret = "******";
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
//var resource_url = "https://stream.twitter.com/1/statuses/filter.json?track=obama&include_entities=1&language=en";
//var resource_url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
var resource_url = "https://stream.twitter.com/1.1/statuses/filter.json";
//var screen_name = "femitfash";
// create oauth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version
//,Uri.EscapeDataString(screen_name)
);
baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
// make the request
ServicePointManager.Expect100Continue = false;
var postBody = "track=obama&include_entities=1&language=en"; // "screen_name=" + Uri.EscapeDataString(screen_name);//
resource_url += "?" + postBody;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
WebResponse response = request.GetResponse();
string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
try include your query string to baseString:
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&track={6}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
Uri.EscapeDataString(valueToTrack)
);
....
var postBody = "track=obama";
https://dev.twitter.com/docs/auth/creating-signature says:
5. Percent encode the parameter string and append it to the output string.
I'm trying to connect to twitter api from my c# application using the "GET" requests. I read the following article:
http://www.codeproject.com/Articles/247336/Twitter-OAuth-authentication-using-Net
Which works great with me and I'm able to post a tweet successfully. But When I try to use it with "GET" and the Twitter API 1.1, it keeps giving me the error 'UnAuthorized'
This is my code:
var oauth_token = "";
var oauth_token_secret = "";
var oauth_consumer_key = "";
var oauth_consumer_secret = "";
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
// message api details
var Id = "111111111111111";// the ID of the tweet need to get info about it
var resource_url = "https://api.twitter.com/1.1/statuses/show.json";
// create oauth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
Uri.EscapeDataString(status)
);
baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url + "?id=" + Id);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";// "POST";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
StreamReader s = new StreamReader(response.GetResponseStream(), encode);
string test = s.ReadLine();
Can you help me of how to edit it to be working with "GET"?
Thank you,