使用asp.net webforms(mvc)进行身份验证和获取Twitter推文

时间:2018-03-09 06:27:17

标签: api asp.net-web-api twitter async-await

AuthorizeAndGetTweets.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;
using Jil;

namespace locationapi.Models
{
    public class AuthorizeAndGetTweets
    { 
       async static public Task<string> whatToName()
        {
            string customerKey = "K3TfA3pIB9F2zibelScwwRy24";
            string secretKey = "2mBJJk74MOmUV3byb0WP76iOmA1xsUkcYnb0ZUh9quPxJVdiwc";


            string screenName = "Manisha_PL";
            // string screenName = "narendramodi";
            string count = "10";

            string tweets = await AuthorizeAndGetTweets.getTweets(customerKey, secretKey, screenName, count);
            // Console.WriteLine("Printing \n" + tweets);
            var serializer = new JavaScriptSerializer();
            dynamic json = serializer.Deserialize<object>(tweets);
            //var enumerableTwitts = (json as IEnumerable<dynamic>);
            IEnumerable<dynamic> enumerableTwitts = (json as IEnumerable<dynamic>);

            //foreach (dynamic d in enumerableTwitts)
            //{
            //    Console.WriteLine(d["text"].ToString());
            //    if (d["place"] != null)
            //    {
            //        Console.WriteLine(d["place"]["full_name"].ToString());
            //    }

            //    //dynamic obj = serializer.Deserialize<object>(d["place"]);
            //    //Console.WriteLine(obj["full_name"]);

            //}
            return tweets;
        }

       public async static Task<string> getTweets(string customerKey, string secretKey, string screenName, string count, string token = null)
        {

            if (token == null)
            {

                token = await authenticate(customerKey, secretKey);
            }


           // Console.WriteLine("token inside function" + token);
            HttpRequestMessage requestingTweets = new HttpRequestMessage(HttpMethod.Get, string.Format("https://api.twitter.com/1.1/statuses/user_timeline.json?count={0}&screen_name={1}&trim_user=1&exclude_replies=1", count, screenName));
            requestingTweets.Headers.Add("Authorization", "Bearer " + token);
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage tweets = await httpClient.SendAsync(requestingTweets);
            string tweetsstring = await tweets.Content.ReadAsStringAsync();


            //Console.WriteLine(tweetsstring);
            //---------------------
            //var serializer = new JavaScriptSerializer();
            //dynamic wholeResponse = serializer.Deserialize<object>(tweetsstring);
            //var enumerableWholeResponse = (wholeResponse as IEnumerable<dynamic>);
            //if (enumerableWholeResponse == null)
            //    return null;
            //IEnumerable<User> userList = enumerableWholeResponse.Select(x =>(User) x["user"]);
            //foreach (User u in userList)
            //{

            //    Console.WriteLine(u.id);
            //    Console.WriteLine(u.id_str);
            //}
            //---------------------
            return tweetsstring;




        }
       public  async static Task<string> authenticate(string customerKey, string secretKey)
        {
            HttpClient authenticationClient = new HttpClient();
            HttpRequestMessage authenticationRequestMessage = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token ");
            var customerInfo = Convert.ToBase64String(new UTF8Encoding().GetBytes(customerKey + ":" + secretKey));
            authenticationRequestMessage.Headers.Add("Authorization", "Basic " + customerInfo);
            authenticationRequestMessage.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");
            HttpResponseMessage authenticationResponse = await authenticationClient.SendAsync(authenticationRequestMessage);
            string json = await authenticationResponse.Content.ReadAsStringAsync();
            AuthenticationTokenClass tokens = JSON.Deserialize<AuthenticationTokenClass>(json);
            //Console.WriteLine(tokens.access_token);
            //Console.WriteLine(tokens.token_type);
            return tokens.access_token;

            //var serializer = new JavaScriptSerializer();
            //dynamic item = serializer.Deserialize<object>(json);
            //Console.WriteLine(json);
            //return item["access_token"];


        }
    }
}

TweetAndLocationController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Script.Serialization;
using locationapi.Models;

namespace locationapi.Controllers
{
    public class TweetAndLocationController : ApiController
    {
       public string Get()
        {
            return AuthorizeAndGetTweets.whatToName().Result;
            //List<string> list = new List<string>();
            //list.Add("Hello");
            //list.Add("World");
            //return list;

        }
    }
}

当我调试代码时,控件直到  HttpResponseMessage tweets =等待httpClient.SendAsync(requesTweets); 在authorizeAndGetTweets.cs

我根本没有得到输出,浏览器显示加载符号。

我哪里错了。我该怎么办?

0 个答案:

没有答案