.Net Twitter OAuth how to perform a successful GET request

亡梦爱人 提交于 2020-01-05 02:34:14

问题


Following this tutorial I was able to perform a successful post to the Twitter API and update my status.

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

However I am having trouble processing a successful GET request. I am trying to modify the Post request to accomplish this but keep getting "Invalid Protocol" errors on my web exception.

The following is the working code that will Post a status update. https://dev.twitter.com/docs/api/1.1/post/statuses/update

I tried to modify the code to perfrom the following GET request https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline

I know I need to add the screen_name or user id parameter that the get request requires. I need to change the base format and string to contain the correct parameters and request. I tried adding the screen name to the headerformat and auth header. (not sure if needed) And If I understand correctly get requests don't require a body.

I tinkered with this code for a while trying to convert it to a get request without success.

How is it done?

Working Post request

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

My nonworking attempt at a Get request

 //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:


You do not have to pass the screen name parameter through the header. Pass it as a query string to the request URL:

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

UPDATE: This is completely untested so I apologize if there are some errors. (I use DotNetOpenAuth in my application so I don't have to worry about these OAuth details.) Most of the following is your code from your question, just made a few changes to it. Also, be sure to use the Twitter API Console to test all your calls to see if they are valid.

//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


来源:https://stackoverflow.com/questions/13515969/net-twitter-oauth-how-to-perform-a-successful-get-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!