如何通过api 1.1获得Twitter头像?

时间:2013-06-13 10:30:43

标签: c# twitter

我只知道twitter用户的screen_name和ID。我想得到像这样的推特头像图像;

https://api.twitter.com/1/users/profile_image?screen_name=StackExchange&size=bigger

我怎么能用twitter api 1.1做到这一点?

1 个答案:

答案 0 :(得分:2)

好的,这就是。

您必须添加Twitter发布的密钥,密码和屏幕名称。

这将返回您需要的json,我将其传递回我的应用程序并使用我在api更改之前的习惯。

        var oAuthConsumerKey = "key";
        var oAuthConsumerSecret = "secret";
        var oAuthUrl = "https://api.twitter.com/oauth2/token";
    var screenname = "StackExchange";

    // 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 avatar
        var avatarFormat =
            "https://api.twitter.com/1.1/users/show.json?screen_name={0}";
        var avatarUrl = string.Format(avatarFormat, screenname);
        HttpWebRequest avatarRequest = (HttpWebRequest)WebRequest.Create(avatarUrl);
        var timelineHeaderFormat = "{0} {1}";
        avatarRequest.Headers.Add("Authorization",
                                    string.Format(timelineHeaderFormat, twitAuthResponse.token_type,
                                                  twitAuthResponse.access_token));
        avatarRequest.Method = "Get";
        WebResponse timeLineResponse = avatarRequest.GetResponse();

        var avatarJson = string.Empty;
        using (authResponse)
        {
            using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
            {
                avatarJson = reader.ReadToEnd();
            }
        }