Error 401 Unauthorized while using Streaming API


#1

Hello,
I have some problem with authentication while using Streaming API.

I am currently using following code for .NET.

string username = “twitter_Username”;
string password = “twitter_Password”;
string authHeader = “OAuth oauth_consumer_key=‘XXXXXXXXXXXXXXXXXXXXXX’, oauth_nonce=‘XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX’, oauth_signature=‘XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX’, oauth_signature_method=‘HMAC-SHA1’, oauth_timestamp=‘1373352690’, oauth_token=‘XXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX’, oauth_version=‘1.0’”;
string parameters = “&track=twitter”;

Encoding encode = System.Text.Encoding.GetEncoding(“utf-8”);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(“https://stream.twitter.com/1.1/statuses/filter.json”);
webRequest.Credentials = new NetworkCredential(username, password);
webRequest.Timeout = -1;
webRequest.Method = “POST”;
webRequest.ContentType = “application/x-www-form-urlencoded”;
webRequest.Headers.Add(“Authorization”, authHeader);

byte[] _twitterTrack = encode.GetBytes(parameters);

webRequest.ContentLength = _twitterTrack.Length;
Stream _twitterPost = webRequest.GetRequestStream();
_twitterPost.Write(_twitterTrack, 0, _twitterTrack.Length);
_twitterPost.Close();

HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

When I execute this code, I get “Error 401 Unauthorized”.
Can anyone help me to overcome with this problem?

Thank you.


#2

In this case it looks like you’re just copying a signature (maybe from the OAuth tool?) into your request. There are many reasons this won’t work, mostly because OAuth requests contain a timestamp and expire after a set amount of time. Each request you send needs to contain a new signature, generated from the data in your request.

I suggest checking out the .NET sections of https://dev.twitter.com/docs/twitter-libraries to find a library which will help you generate an OAuth request - it’s difficult to do correctly by hand but there are plenty of third party packages which have figured the signing process out.


#3

Is there any php library in -Libraries built for HTTP with OAuth that should also work with Twitter- section?


#4

Yes, there are a few. I like https://github.com/themattharris/tmhOAuth since it is written by a Twitter employee and is pretty robust.


#5

Hi I am getting same error while using “http://twitter.com/account/verify_credentials.json” API.Can anyone help me out.

Thanks