1

I would like to consume parts of the Twitter API from a controller so that I can serve the content without the user having javascript enabled.

I plan on creating a proxy controller to manage the API uri's and authentication token but I am unsure on how to make the actual service calls from the backend. I would prefer to copy the returned data into entity objects so I can format them easily in the view.

Are there examples of this or documentation on the set of classes I will need to use?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Smith
  • 2,904
  • 3
  • 19
  • 25

2 Answers2

4

If you want to create a web request, this is an example:

(pData can be parameters for web api)

    private string _callWebService(string pUrl, string pData)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pUrl);
            request.Method = "POST";
            request.ContentType = "...";
            byte[] bytes = Encoding.UTF8.GetBytes(pData);
            request.ContentLength = bytes.Length;

            using (var writer = request.GetRequestStream())
            {
                writer.Write(bytes, 0, bytes.Length);
            }

            using(var response = (HttpWebResponse)request.GetResponse())
            {
                 if (response.StatusCode.ToString().ToLower() == "ok")
                 {
                    using(var contentReader = new StreamReader(response.GetResponseStream()))
                    {
                        return contentReader.ReadToEnd();
                    }
                 }
             }
        }
        catch (Exception)
        {
            return string.Empty;
        }
        return string.Empty;
    }
MRB
  • 3,752
  • 4
  • 30
  • 44
  • Thanks a lot. I will use this to get started. – Smith Jan 14 '14 at 20:35
  • @JohnSaunders Thank you for the heads up. I updated my answer, Is it ok now? (for exceptions, i use `Empty` because it is only an example) – MRB Jan 15 '14 at 05:17
0

The actual code you need to use is below, this authenticates and retrieves a user's timeline.

It's taken from my question last year, I have working examples of an MVC project in the Github project mentioned in the question and a nuget install. You can use the nuget package or just copy the code from Github.

Authenticate and request a user's timeline with Twitter API 1.1 oAuth

// 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; }
}
Community
  • 1
  • 1
hutchonoid
  • 32,982
  • 15
  • 99
  • 104
  • Actually, if it has the same answer, isn't it a duplicate of http://stackoverflow.com/questions/17067996/authenticate-and-request-a-users-timeline-with-twitter-api-1-1-oauth? – John Saunders Jan 14 '14 at 21:49