47

This morning I have received the dreaded 'The Twitter REST API v1 is no longer active. Please migrate to API v1.1.' error in a few of my web sites.

Previously I have been using javascript/json to make these calls to http://api.twitter.com/1/statuses/user_timeline.json? to display a timeline.

As this is no longer available I need to adopt the new 1.1 API process.

I need to do the following using HttpWebRequest objects not a 3rd party application:

  1. Authenticate using oauth key and secret
  2. Make an authenticated call to pull back to display users timeline
hutchonoid
  • 32,982
  • 15
  • 99
  • 104
  • A mixture, I have traditional and mvc. – hutchonoid Jun 12 '13 at 14:57
  • Have you seen **[this](http://stackoverflow.com/questions/12479575/how-to-generate-oauth-signature-with-c-sharp-for-twitter-api-1-1)**? There's also a list of third party libraries on the twitter dev site - there are a few C# ones. – Jimbo Jun 12 '13 at 16:09
  • @Jimbo Hi, yes thanks. I need to avoid 3rd party libraries. The reason being that I need to use it in many different type of applications (mvc and traditional apps), CMS, portals etc. I've almost done it, I'll post the answer if it works. – hutchonoid Jun 12 '13 at 16:59
  • @hutchonoid Is it possible to do a keyword search for all user in a WebForm ??? – Phill Healey Jun 08 '14 at 19:02
  • @PhillHealey Yes, I believe you can. Basically anything that is available from the twitter api can be exposed although you may have to extend/modify the source on github. – hutchonoid Jun 10 '14 at 15:02

2 Answers2

103

Here is what I did to get this working in a simple example.

I had to generate an oAuth consumer key and secret from Twitter at:

https://dev.twitter.com/apps/new

I deserialized the authentication object first to get the token and type back in order to authenticate the timeline call.

The timeline call simply reads the json as that is all I need to do, you may want to deserialize it yourself into an object.

I have created a project for this at : https://github.com/andyhutch77/oAuthTwitterWrapper

Update - I have updated the github project to include both asp .net web app & mvc app example demos and nuget install.

// You need to set your own keys and screen name
var oAuthConsumerKey = "superSecretKey";
var oAuthConsumerSecret = "superSecretSecret";
var oAuthUrl = "https://api.twitter.com/oauth2/token";
var screenname = "aScreenName";

// Do the Authenticate
var authHeaderFormat = "Basic {0}";

var authHeader = string.Format(authHeaderFormat,
    Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
    Uri.EscapeDataString((oAuthConsumerSecret)))
));

var postBody = "grant_type=client_credentials";

HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using (Stream stream = authRequest.GetRequestStream())
{
    byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
    stream.Write(content, 0, content.Length);
}

authRequest.Headers.Add("Accept-Encoding", "gzip");

WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
TwitAuthenticateResponse twitAuthResponse;
using (authResponse)
{
    using (var reader = new StreamReader(authResponse.GetResponseStream())) {
        JavaScriptSerializer js = new JavaScriptSerializer();
        var objectText = reader.ReadToEnd();
        twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(objectText);
    }
}

// Do the timeline
var timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5";
var timelineUrl = string.Format(timelineFormat, screenname);
HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl);
var timelineHeaderFormat = "{0} {1}";
timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
timeLineRequest.Method = "Get";
WebResponse timeLineResponse = timeLineRequest.GetResponse();
var timeLineJson = string.Empty;
using (timeLineResponse)
{
    using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
    {
         timeLineJson = reader.ReadToEnd();
    }
}


public class TwitAuthenticateResponse {
    public string token_type { get; set; }
    public string access_token { get; set; }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
hutchonoid
  • 32,982
  • 15
  • 99
  • 104
  • 10
    You should shove this into a class and put it on github for others to use ;) – Jimbo Jun 12 '13 at 17:30
  • 1
    Thanks a million for sharing this - it really helped me get back up and running quickly! One suggestion with your solution would be to allow parameters to be passed into the OAuthTwitterWrapper object either through the constructor, or by making the properties public. In my case, I wanted to be able to vary the number of tweets to show depending on the real estate available on the page. All the same, a nice solution and thanks! – John Mc Jul 11 '13 at 17:47
  • No problem, it's good to see it being used. I will add those changes to the project that you suggest. Many thanks. – hutchonoid Jul 11 '13 at 18:58
  • Wow that was fast! Thanks :-) – John Mc Jul 12 '13 at 13:25
  • No problem, let me know if you find any bugs.:) – hutchonoid Jul 12 '13 at 13:41
  • 5
    Awesome post, this should be on Twitter docs page, far easier to understand! – timothyclifford Jul 19 '13 at 01:38
  • @timothyclifford thanks, I must admit I struggled with the twitter docs too. – hutchonoid Jul 19 '13 at 05:55
  • @hutchonoid would it be possible to get this as a dll for .net 2.0? i downloaded the solution from github, but don't see a dll and don't know how to make that code into a dll. Thanks! – kylemac Jul 23 '13 at 01:31
  • @kylemac you should be able to get the dll by creating a project and adding it via nuget. Te URL is on GitHub, or just download it outside of a project & rename the package to a zip. It will be in there. – hutchonoid Jul 23 '13 at 06:10
  • thanks @hutchonoid. I was able to get the dll, but it is .net 4 and the project i'm updating is in .net 2.0... is it possible to put this in 2.o? (I see the newtonsoft comes in multiple versions.) – kylemac Jul 23 '13 at 14:51
  • @kylemac No problem, sorry but I don't have a dev environment setup to release a .net 2.0 version. You could fork my project and create a one. I'm sure it won't be too difficult. – hutchonoid Jul 26 '13 at 12:54
  • You've saved me a lot of hassle here mate! –  Nov 25 '13 at 16:15
  • @DeeMac Good to hear, I was amazed I couldn't find anything online at the time. – hutchonoid Nov 25 '13 at 16:18
  • Well I've been trying for a while now with the advice from several other articles (http://umerpasha.wordpress.com/2013/06/13/c-code-to-get-latest-tweets-using-twitter-api-1-1/), but they all deal with tokens in a different way, none of which have worked up to now. I should possibly have put my energy into investigating why they're not working for me (seem to be working for everyone else) but I don't wish to waste time when your alternative does the job first time without any probs. –  Nov 25 '13 at 16:30
  • No problem. :) @do4urka – hutchonoid Jul 11 '15 at 20:37
  • Thanks for this, nice and easy to follow :) – Stephen Garside Jul 07 '16 at 09:40
  • @StephenGarside No problem. :) – hutchonoid Jul 07 '16 at 09:52
  • Hey How can I use it to post a tweet ? I'm doing something like this string status = "Test tweet"; string tweetUrl = "https://api.twitter.com/1.1/statuses/update.json?status="+status; HttpWebRequest tweetRequest = (HttpWebRequest)WebRequest.Create(tweetUrl); var tweetHeaderFormat = "{0} {1}"; tweetRequest.Headers.Add("Authorization", string.Format(tweetHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token)); tweetRequest.Method = "POST"; WebResponse tweetResponse = tweetRequest.GetResponse(); – sohaib javed Oct 05 '16 at 05:44
  • @sohaibjaved Hi, sorry I've not posted a one, I'd have to check myself. – hutchonoid Oct 05 '16 at 08:25
  • The "JavaScriptSerializer js = new JavaScriptSerializer();" doesn't really do anything. Maybe you can take that one out for the sake of clarity? – Niels Apr 03 '17 at 15:28
1

Created a JS only solution to get Twitter posts on your site without using new API - can now specify number of tweets too: http://goo.gl/JinwJ

Jason
  • 41
  • 1