如何为Vimeo api生成正确的oauth_signature?

时间:2011-08-04 13:03:40

标签: c# api oauth signature vimeo

我的错误无效oauth_signature:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Web;



namespace ConsoleApplication1
{
    class Program
    {
         static void Main(string[] args)
        {
            var time_stamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
            string consumer_key = "MyConsumerKey";
            string signature_method = "HMAC-SHA1";
            string nonce = RandomString(32);
            string signature;

            string key = "MyConsumerSecret&";
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            //hm.Key = key;
            //HMACSHA1.Create().Initialize();
            byte[] keyByte = encoding.GetBytes(key);
            string baseUrl = String.Format("method=vimeo.people.search&oauth_consumer_key={0}&oauth_signature_method=HMAC-SHA1&oauth_timestamp={1}&oauth_version=1.0", consumer_key, time_stamp);
            byte[] baseMessage = encoding.GetBytes(baseUrl);
            HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
            byte[] hashmessage = hmacsha1.ComputeHash(baseMessage);
            byte[] encode = System.Text.ASCIIEncoding.ASCII.GetBytes(hashmessage.ToString());
            signature = System.Convert.ToBase64String(encode);

            Console.WriteLine("signature:  " + signature); 
            string url = String.Format("http://vimeo.com/api/rest/v2?method=vimeo.videos.search&query=ssaa&api_key=API_KEY&oauth_consumer_key={0}&oauth_version=1.0&oauth_signature_method={1}&oauth_timestamp={2}&oauth_nonce={3}&oauth_token=478fa9c8bc5834e60a4fae7688aa0c8e&oauth_signature={4}", consumer_key, signature_method, time_stamp, nonce,signature);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            StreamReader stream = new StreamReader(resp.GetResponseStream());
            string html = stream.ReadToEnd();
            Console.WriteLine(html);
        }

        private static string RandomString(int size)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }

            return builder.ToString();
        }
    }
}

0 个答案:

没有答案