Quantcast
Channel: Welcome To The Rhizohm - Twitter
Viewing all articles
Browse latest Browse all 6

Getting Twitter Profile Image Via C# With 1.1 API

$
0
0

If you know someone's Twitter handle and would like to display their twitter avatar on your website, here's some code to get the URL of their avatar.  First, you'll need to register at http://dev.twitter.com and acquire a ConsumerKey, ConsumerSecret, Token and TokenSecret -- now that Twitter supports application only authentication, there isn't any handshaking involved; you just need to craft up the right OAuthCredentials for a ProtectedResource, which the Hammock library does for you. Love that library: you can get it here: https://github.com/danielcrenna/hammock or grab it as a NuGet package: http://nuget.org/packages/Hammock

Here’s the code; nothing too fancy:

using System;using Hammock;using Hammock.Authentication.OAuth;using Hammock.Web;using Newtonsoft.Json.Linq;namespace ExternalServices
{publicclass TwitterAvatarLookup : ITwitterAvatarLookup
    {conststring ConsumerKey = "";conststring ConsumerSecret = "";conststring Token = "";conststring TokenSecret = "";publicstring GetTwitterAvatarUrl(string twitterHandle)
        {string avatarUrl = string.Empty;
            var request = new RestRequest
            {
                Credentials = new OAuthCredentials
                {
                    Type = OAuthType.ProtectedResource,
                    SignatureMethod = OAuthSignatureMethod.HmacSha1,
                    ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                    ConsumerKey = ConsumerKey,
                    ConsumerSecret = ConsumerSecret,
                    Token = Token,
                    TokenSecret = TokenSecret,
                }
            };
            request.Path =string.Format("https://api.twitter.com/1.1/users/lookup.json?screen_name={0}&include_entities=0&include_rts=0",
                    twitterHandle);

            request.Method = WebMethod.Get;
            RestClient client = new RestClient();try
            {
                RestResponse response = client.Request(request);
                JArray jArray = JArray.Parse(response.Content);
                avatarUrl = (string)jArray[0]["profile_image_url_https"];

            }
            catch (Exception)
            {return"default.png";
            }return avatarUrl;
        }

    }
}

If you know more than one handle whose avatar you need to get, the API supports passing multiple user handles; see https://dev.twitter.com/docs/api/1.1/get/users/lookup


Viewing all articles
Browse latest Browse all 6

Latest Images

Trending Articles





Latest Images