Autenticar y solicitar la línea de tiempo de un usuario con Twitter API 1.1 oAuth

Resuelto hutchonoid asked hace 11 años • 2 respuestas

Esta mañana recibí el temido mensaje 'La API REST v1 de Twitter ya no está activa'. Migre a API v1.1.' error en algunos de mis sitios web.

Anteriormente he estado usando javascript/json para realizar estas llamadas a http://api.twitter.com/1/statuses/user_timeline.json . para mostrar una línea de tiempo.

Como ya no está disponible, necesito adoptar el nuevo proceso API 1.1.

Necesito hacer lo siguiente usando objetos HttpWebRequest, no una aplicación de terceros:

  1. Autenticar usando clave oauth y secreto
  2. Realice una llamada autenticada para retroceder y mostrar la línea de tiempo de los usuarios
hutchonoid avatar Jun 12 '13 21:06 hutchonoid
Aceptado

Esto es lo que hice para que esto funcionara en un ejemplo simple.

Tuve que generar una clave de consumidor de oAuth y un secreto de Twitter en:

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

Primero deserialicé el objeto de autenticación para obtener el token y escribí nuevamente para autenticar la llamada de la línea de tiempo.

La llamada de la línea de tiempo simplemente lee el json, ya que eso es todo lo que necesito hacer; es posible que desees deserializarlo tú mismo en un objeto.

He creado un proyecto para esto en: https://github.com/andyhutch77/oAuthTwitterWrapper

Actualización : actualicé el proyecto github para incluir demostraciones de ejemplo de la aplicación web asp .net y la aplicación mvc y la instalación de nuget.

// 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; }
}
hutchonoid avatar Jun 12 '2013 17:06 hutchonoid

Creé una solución exclusiva de JS para obtener publicaciones de Twitter en su sitio sin utilizar la nueva API; ahora también puede especificar la cantidad de tweets: http://goo.gl/JinwJ

Jason avatar Jun 14 '2013 16:06 Jason