.Net Twitter OAuth如何执行成功的GET请求

时间:2012-11-22 15:36:01

标签: .net asp.net-mvc oauth twitter twitter-oauth

按照本教程,我能够成功发布Twitter API并更新我的状态。

http://www.codeproject.com/Articles/247336/Twitter-OAuth-authentication-using-Net?fid=1649027&df=90&mpp=25&noise=3&prof=False&sort=Position&view=Quick&spc=Relaxed&fr=26#xx0xx

但是我在处理成功的GET请求时遇到问题。我正在尝试修改Post请求以完成此操作,但在我的Web异常中不断出现“无效协议”错误。

以下是发布状态更新的工作代码。 https://dev.twitter.com/docs/api/1.1/post/statuses/update

我尝试修改代码以执行以下GET请求 https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline

我知道我需要添加get请求所需的screen_name或user id参数。 我需要更改基本格式和字符串以包含正确的参数和请求。 我尝试将屏幕名称添加到headerformat和auth标头。 (不确定是否需要) 如果我理解正确,请求不需要正文。

我修改了这段代码一段时间试图将其转换为get请求但没有成功。

怎么做?

工作发布请求

 public ActionResult Test2()
    {
        //Auth

        var oauth_token = "161946489-uLEUgIqbQ...";  //user
        var oauth_token_secret = "kVfAfW6GIbfc....";
        var oauth_consumer_key = "kvXJFgjsLGKs...";  //this is my app
        var oauth_consumer_secret = "2cgBSQyZS...";

        //Request details

        var oauth_version = "1.0";
        var oauth_signature_method = "HMAC-SHA1";
        var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
        var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
        var resource_url = "https://api.twitter.com/1.1/statuses/update.json";
        var status = "Updating status via REST API if this works again";
        //var screen_name = "ScreenName";

        //encrypted oAuth signature

        var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
            "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}";

        var baseString = string.Format(baseFormat,
                                    oauth_consumer_key,
                                    oauth_nonce,
                                    oauth_signature_method,
                                    oauth_timestamp,
                                    oauth_token,
                                    oauth_version,
                                    Uri.EscapeDataString(status)
                                    );

        baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url),
                     "&", Uri.EscapeDataString(baseString));

        //Encrypt data

        var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                    "&", Uri.EscapeDataString(oauth_token_secret));

        string oauth_signature;
        using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
        {
            oauth_signature = Convert.ToBase64String(
                hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
        }

        //Finish Auth header

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

        var authHeader = string.Format(headerFormat,
                                Uri.EscapeDataString(oauth_nonce),
                                Uri.EscapeDataString(oauth_signature_method),
                                Uri.EscapeDataString(oauth_timestamp),
                                Uri.EscapeDataString(oauth_consumer_key),
                                Uri.EscapeDataString(oauth_token),
                                Uri.EscapeDataString(oauth_signature),
                                Uri.EscapeDataString(oauth_version)
                        );

        //Disable exprect 100 continue header

        var postBody = "status=" + Uri.EscapeDataString(status);

        ServicePointManager.Expect100Continue = false;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
        request.Headers.Add("Authorization", authHeader);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        using (Stream stream = request.GetRequestStream())
        {
            byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
            stream.Write(content, 0, content.Length);
        }
        try
        {
            WebResponse response = request.GetResponse();
            ViewBag.Message = response.ToString();
        }
        catch (WebException e)
        {
            ViewBag.Message = e.Status;
        }

我在Get请求中的非工作尝试

 //Request details

        var oauth_version = "1.0";
        var oauth_signature_method = "HMAC-SHA1";
        var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
        var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
        var resource_url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
        var status = "Updating status via REST API if this works again";
        var screen_name = "Starcraft2foru";

 //encrypted oAuth signature

    var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
        "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}";

    var baseString = string.Format(baseFormat,
                                oauth_consumer_key,
                                oauth_nonce,
                                oauth_signature_method,
                                oauth_timestamp,
                                oauth_token,
                                oauth_version,
                                Uri.EscapeDataString(screen_name)
                                );

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

    //Encrypt data

    var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                "&", Uri.EscapeDataString(oauth_token_secret));

    string oauth_signature;
    using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
    {
        oauth_signature = Convert.ToBase64String(
            hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
    }

    //Finish Authentification header

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

    var authHeader = string.Format(headerFormat,
                            Uri.EscapeDataString(oauth_nonce),
                            Uri.EscapeDataString(oauth_signature_method),
                            Uri.EscapeDataString(oauth_timestamp),
                            Uri.EscapeDataString(oauth_consumer_key),
                            Uri.EscapeDataString(oauth_token),
                            Uri.EscapeDataString(oauth_signature),
                            Uri.EscapeDataString(oauth_version),
                            Uri.EscapeDataString(screen_name)
                    );

    //Disable exprect 100 continue header

    var postBody = "screen_name=" + Uri.EscapeDataString(screen_name);

    ServicePointManager.Expect100Continue = false;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
        request.Headers.Add("Authorization", authHeader);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        /*using (Stream stream = request.GetRequestStream())
        {
            byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
            stream.Write(content, 0, content.Length);
        }
        */
        try
        {
            WebResponse response = request.GetResponse();
            ViewBag.Message = response.ToString();
        }
        catch (WebException e)
        {
            ViewBag.Message = e.Status;
        }

1 个答案:

答案 0 :(得分:2)

您不必通过标题传递屏幕名称参数。将其作为查询字符串传递给请求URL:

https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=Starcraft2foru

更新:这是完全未经测试的,所以如果有错误我会道歉。 (我在我的应用程序中使用DotNetOpenAuth,因此我不必担心这些OAuth详细信息。)以下大部分内容都是您的问题中的代码,只是对其进行了一些更改。另外,请务必使用Twitter API Console来测试所有来电,看看它们是否有效。

//Request details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
var resource_url = "https://api.twitter.com/1.1/statuses/user_timeline.json

//encrypted oAuth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
    "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";

var baseString = string.Format(baseFormat,
                            oauth_consumer_key,
                            oauth_nonce,
                            oauth_signature_method,
                            oauth_timestamp,
                            oauth_token,
                            oauth_version
                            );

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

//Encrypt data

var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
            "&", Uri.EscapeDataString(oauth_token_secret));

string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
    oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}

//Finish Authentification header

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

var authHeader = string.Format(headerFormat,
                        Uri.EscapeDataString(oauth_nonce),
                        Uri.EscapeDataString(oauth_signature_method),
                        Uri.EscapeDataString(oauth_timestamp),
                        Uri.EscapeDataString(oauth_consumer_key),
                        Uri.EscapeDataString(oauth_token),
                        Uri.EscapeDataString(oauth_signature),
                        Uri.EscapeDataString(oauth_version)
                );

//Disable exprect 100 continue header
ServicePointManager.Expect100Continue = false;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";

WebResponse response = request.GetResponse();
string responseData;

using(StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    responseData = reader.ReadToEnd();
}

return responseData; // Or do whatever you want with the response