twitter授权服务器在MVC4中从twitter获取数据的请求格式是什么

时间:2014-01-06 10:34:47

标签: c# asp.net asp.net-mvc asp.net-mvc-4 twitter-oauth

public dynamic GetUserInfo(string authToken)
{
    var userInfoUrl = "https://api.twitter.com/1.1/account/verify_credentials.json";
    var hc = new HttpClient();

    string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    string oauthtimestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
    string oAuthHeader = "Authorization: OAuth oauth_consumer_key='VGu26AeM14lLWcUc9mdZQ', oauth_nonce='" + oauthnonce + "', oauth_signature='ZQvom%2BHjpiV63yIRnAf%2Ft6pN6wM%3D', oauth_signature_method='HMAC-SHA1', oauth_timestamp='" + oauthtimestamp + "', oauth_token='" + authToken + "', oauth_version='1.0'";
    hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", oAuthHeader);
    var response = hc.GetAsync(userInfoUrl).Result;
    dynamic userInfo = response.Content.ReadAsAsync<dynamic>().Result;
    return userInfoUrl;
    //return 0;
}

1 个答案:

答案 0 :(得分:1)

// 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);
    }
}

Authenticate and request a user's timeline with Twitter API 1.1 oAuth