ASP.NET Twitter api 1.1

step 1.

트위터 api를 사용하려면 인증된 아이디가 필요하다.

— 참고 페이지 —
인증 받는 법 : Twitter API v1.1 with OAuth
인증 받는 곳 : 트위터 개발자 페이지

step 2.

트위터 서비스 관련 함수
구글링을 통해 가져온 소스가 다수 포함되어 있으나, 정확한 출처를 기억하지 못해 적지 못하였습니다. 출처 아시는 분은 제보 부탁드려요.

/// <summary>
        /// 트위터 API 접속 ID 등 세팅
        /// </summary>
        public void SetTwitterApi(string _consumerkey, string _consumersecret, string _accesstoken, string _accesssecret)
        {
            this.consumerkey = _consumerkey;
            this.consumersecret = _consumersecret;
            this.accesstoken = _accesstoken;
            this.accesssecret = _accesssecret;
        }

        public DataTable GetTwiter(int cnt)
        {
            #region api 1.1

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=받은 아이디");
            sb.AppendLine("&trim_user=false");
            sb.AppendLine("&count=" + cnt + "");

            //트위터 개발자 사이트에서 얻은 값을 입력.
            string oauthconsumerkey = "";
            string oauthconsumersecret = "";
            string oauthtoken = "";
            string oauthtokensecret = "";

            SetTwitterApi(oauthconsumerkey, oauthconsumersecret, oauthtoken, oauthtokensecret);
            string jsonStrTimeline = GetTwitterData(sb.ToString());
            JsonTextParser parser = new JsonTextParser();
            JsonArrayCollection jArr = parser.Parse(jsonStrTimeline) as JsonArrayCollection;

            dt.Columns.Add(new DataColumn("ID", typeof(string)));                               // 트위터 글번호
            dt.Columns.Add(new DataColumn("TEXT", typeof(string)));                             // 트위터 내용
            dt.Columns.Add(new DataColumn("CREATED_AT", typeof(string)));                       // 작성일자
            dt.Columns.Add(new DataColumn("PROFILE_IMAGE_URL", typeof(string)));                // 프로파일 이미지

            DataRow dr = null;
            foreach (JsonCollection twit in jArr)
            {
                dr = dt.NewRow();
                dr[0] = twit[2].GetValue();
                dr[1] = twit[3].GetValue();
                dr[2] = twit[0].GetValue();
                JsonObjectCollection user = twit[11] as JsonObjectCollection;
                dr[3] = user[27].GetValue();
                dt.Rows.Add(dr);
            }

            #endregion

            return dt;
        }

        #endregion

        #region [   트위터 서비스 관련 함수   ]

        private string EncodeCharacters(string data)
        {
            //as per OAuth Core 1.0 Characters in the unreserved character set MUST NOT be encoded
            //unreserved = ALPHA, DIGIT, '-', '.', '_', '~'
            if (data.Contains("!"))
                data = data.Replace("!", "%21");
            if (data.Contains("'"))
                data = data.Replace("'", "%27");
            if (data.Contains("("))
                data = data.Replace("(", "%28");
            if (data.Contains(")"))
                data = data.Replace(")", "%29");
            if (data.Contains("*"))
                data = data.Replace("*", "%2A");
            if (data.Contains(","))
                data = data.Replace(",", "%2C");

            return data;
        }  

        //this gets the json data from twitter api
        public string GetTwitterData(string resourceurl)
        {
            //create parameter list
            List<string> parameterlist;
            //check for query string
            if (resourceurl.Contains("?"))
            {
                parameterlist = getparameterlistfromurl(resourceurl);
                resourceurl = resourceurl.Substring(0, resourceurl.IndexOf('?'));
            }

            else
            {
                parameterlist = null;
            }
            //build the oauth header
            string authheader = buildheader(resourceurl, parameterlist);

            //make the request to the twitter api and get the JSON response
            string jsonresponse = TwitterWebRequest(resourceurl, authheader, parameterlist);

            return jsonresponse;


        }

        //retreive a list if parameters from the resource url. This will be used when making the request to the twitter api and in generating the signature
        private List<string> getparameterlistfromurl(string resourceurl)
        {

            //Uri MyUrl = new Uri(resourceurl);
            string querystring = resourceurl.Substring(resourceurl.IndexOf('?') + 1);

            List<string> listtoreturn = new List<string>();

            NameValueCollection nv = HttpUtility.ParseQueryString(querystring);

            foreach (string parameter in nv)
            {
                listtoreturn.Add(parameter + "=" + Uri.EscapeDataString(nv[parameter].ToString()));

            }
            return listtoreturn;
        }



        //this gets the timeline data from twitter api
        private string buildheader(string resourceurl, List<string> parameterlist)
        {

            string nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            TimeSpan timespan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            string timestamp = Convert.ToInt64(timespan.TotalSeconds).ToString();

            string signature = getSignature(nonce, timestamp, resourceurl, parameterlist);

            // build the authentication header with all information collected

            var HeaderFormat = "OAuth " +
            "oauth_consumer_key=\"{0}\", " +
            "oauth_nonce=\"{1}\", " +
            "oauth_signature=\"{2}\", " +
            "oauth_signature_method=\"{3}\", " +
            "oauth_timestamp=\"{4}\", " +
            "oauth_token=\"{5}\", " +
            "oauth_version=\"{6}\"";

            string authHeader = string.Format(HeaderFormat,
            Uri.EscapeDataString(consumerkey),
            Uri.EscapeDataString(nonce),
            Uri.EscapeDataString(signature),
            Uri.EscapeDataString(signaturemethod),
            Uri.EscapeDataString(timestamp),
            Uri.EscapeDataString(accesstoken),
            Uri.EscapeDataString(version)
            );

            return authHeader;

        }



        private string getSignature(string nonce, string timestamp, string resourceurl, List<string> parameterlist)
        {
            // generate the base string for the signature

            string baseString = generatebasestring(nonce, timestamp, resourceurl, parameterlist);

            baseString = string.Concat("GET&", Uri.EscapeDataString(resourceurl), "&", Uri.EscapeDataString(baseString));


            // generate the signature using the base string, consumer secret and access secret from the application api. Using the HMAC-SHA1 signature method

            var signingKey = string.Concat(Uri.EscapeDataString(consumersecret), "&", Uri.EscapeDataString(accesssecret));
            string signature;

            //generate hash using signing key
            HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(signingKey));

            signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
            //get signature signature using the hash

            return signature;

        }

        private string generatebasestring(string nonce, string timestamp, string resourceurl, List<string> parameterlist)
        {

            string basestring = "";
            //create list with all the security parameters
            List<string> baseformat = new List<string>();
            baseformat.Add("oauth_consumer_key=" + consumerkey);
            baseformat.Add("oauth_nonce=" + nonce);
            baseformat.Add("oauth_signature_method=" + signaturemethod);
            baseformat.Add("oauth_timestamp=" + timestamp);
            baseformat.Add("oauth_token=" + accesstoken);
            baseformat.Add("oauth_version=" + version);


            //append parameter list as twitter requires the parameters to be in alphabetical order
            if (parameterlist != null)
            {
                baseformat.AddRange(parameterlist);

            }
            //sort list alphabetically
            baseformat.Sort();


            //loop through list and generate base string

            foreach (string value in baseformat)
            {
                basestring += value + "&";
            }

            basestring = basestring.TrimEnd('&');

            return basestring;


        }

        //makes the request to twitter and returns a string of JSON data

        private string TwitterWebRequest(string resourceurl, string authheader, List<string> parameterlist)
        {

            //build  the http web request to the twitter api
            ServicePointManager.Expect100Continue = false;

            string postBody;

            if (parameterlist != null)
            {
                postBody = GetPostBody(parameterlist);
            }
            else
            {
                postBody = "";
            }
            resourceurl += "?" + postBody;



            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resourceurl);
            request.Headers.Add("Authorization", authheader);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";

            // Retrieve the response json data
            WebResponse response = request.GetResponse();

            //json reponse data
            string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();

            return responseData;

        }

        private string GetPostBody(List<string> parameterlist)
        {
            string stringtoreturn = "";

            foreach (string item in parameterlist)
            {
                stringtoreturn += item + "&";

            }
            stringtoreturn = stringtoreturn.TrimEnd('&');
            return stringtoreturn;

        }

        #endregion

위 소스 중 아래 부분은 System.Net.Json.dll 파일이 추가 되어야 함.

JSON for.NET Download

JsonTextParser = new JsonTextParser();
JsonArrayCollenction = parser.Parse(jsonStrTimeline) as JsonArrayCollection;

+ Recent posts