65.9K
CodeProject 正在变化。 阅读更多。
Home

Twitter API v1.1 with OAuth

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.89/5 (35投票s)

2013 年 11 月 5 日

CPOL

3分钟阅读

viewsIcon

145040

downloadIcon

17

Twitter API v1.1 with OAuth.

引言   

OAuth 协议使网站或应用程序(消费者)能够通过 API 访问 Web 服务(服务提供商)的受保护资源,而无需用户向消费者披露其服务提供商凭据。更广泛地说,OAuth 创建了一种可自由实现且通用的 API 身份验证方法。 

OAuth 旨在将委托式 Web 服务身份验证的体验和实现统一到一个单一的、社区驱动的协议中。OAuth 基于现有协议和各种网站独立实施的最佳实践。一个开放的标准,同时受到大型和小型提供商的支持,为应用程序开发人员和这些应用程序的用户都提供了统一且值得信赖的体验。

最近 Twitter 发布了 API v1.1,并且已弃用 v1.0 API 支持。

在 v1.1 中,Twitter 在身份验证方面非常严格。我们需要创建一个应用程序来访问 Twitter API。 

OAuth_Authentication_Flow_v1.0

应用程序创建  

要创建应用程序,我们需要在 https://dev.twitter.com/ 上使用我们的 Twitter 凭据登录。

成功登录后,点击“Create a new application”来创建应用程序。

之后,填写下面显示的表单来创建应用程序。

提供应用程序名称、描述、网站 URL 和回调 URL。


 

接受 Twitter 提及的规则和规定,然后点击“Create your Twitter application”以继续,我们将看到下面的屏幕。

现在我们有了 Consumer Key 和 Consumer Secret,但我们没有任何 Access Token 和 Access Token Secret。

因此,要生成/创建访问令牌和访问令牌密钥,请单击下图所示的“Create Access Token”。

我们将看到带有确认的以下屏幕。

太棒了,各位!我们已成功为 Twitter 创建了一个应用程序。

现在是时候编写一些代码来访问 Twitter API 了。

使用代码 

Twitter 提供了许多 API,如果需要,我们可以 在此处 查看。

我们现在来看看代码。

public void Verify_Credentials()
{
    string oauthconsumerkey = "your consumerkey";
    string oauthconsumersecret = "your consumer secret key";
    string oauthsignaturemethod = "HMAC-SHA1";
    string oauthversion = "1.0";
    string oauthtoken = "your oauth token";
    string oauthtokensecret = "your oauth token secret";
    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();
    SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
    basestringParameters.Add("oauth_version", "1.0");
    basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
    basestringParameters.Add("oauth_nonce", oauthnonce);
    basestringParameters.Add("oauth_signature_method", "HMAC-SHA1");
    basestringParameters.Add("oauth_timestamp", oauthtimestamp);
    basestringParameters.Add("oauth_token", oauthtoken);
    //GS - Build the signature string
    StringBuilder baseString = new StringBuilder();
    baseString.Append("GET" + "&");
    baseString.Append(EncodeCharacters(Uri.EscapeDataString("https://api.twitter.com/1.1/account/verify_credentials.json") + "&"));
    foreach (KeyValuePair<string, string> entry in basestringParameters)
    {
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
    }

    //Since the baseString is urlEncoded we have to remove the last 3 chars - %26
    string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);

    //Build the signing key
    string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
    EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));

    //Sign the request
    HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
    string oauthsignature = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));

    //Tell Twitter we don't do the 100 continue thing
    ServicePointManager.Expect100Continue = false;

    //authorization header
    HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(
      @"https://api.twitter.com/1.1/account/verify_credentials.json");
    StringBuilder authorizationHeaderParams = new StringBuilder();
    authorizationHeaderParams.Append("OAuth ");
    authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
    authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
    authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
    authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
    if (!string.IsNullOrEmpty(oauthtoken))
        authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\",");
    authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
    authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
    hwr.Headers.Add("Authorization", authorizationHeaderParams);
    hwr.Method = "GET";
    hwr.ContentType = "application/x-www-form-urlencoded";

    //Allow us a reasonable timeout in case Twitter's busy
    hwr.Timeout = 3 * 60 * 1000;
    try
    {
        hwr.Proxy = new WebProxy("enter proxy details/address");
        HttpWebResponse rsp = hwr.GetResponse() as HttpWebResponse;
        Stream dataStream = rsp.GetResponseStream();
        //Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        //Read the content.
        string responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
       
    }
}

我们可以 在此处 查看此 API 的描述。

public void Search()
{
    string url = "https://api.twitter.com/1.1/search/tweets.json?q=your search query";
    string oauthconsumerkey = "your consumer key";
    string oauthtoken = "your oauth token";
    string oauthconsumersecret = "your consumer secret";
    string oauthtokensecret = "your oauth token secret";
    string oauthsignaturemethod = "HMAC-SHA1";
    string oauthversion = "1.0";
    string oauthnonce = 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 oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
    SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
    basestringParameters.Add("q", "your search query");
    basestringParameters.Add("oauth_version", oauthversion);
    basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
    basestringParameters.Add("oauth_nonce", oauthnonce);
    basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
    basestringParameters.Add("oauth_timestamp", oauthtimestamp);
    basestringParameters.Add("oauth_token", oauthtoken);
    //Build the signature string
    StringBuilder baseString = new StringBuilder();
    baseString.Append("GET" + "&");
    baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
    foreach (KeyValuePair<string, string> entry in basestringParameters)
    {
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
    }

    //Remove the trailing ambersand char last 3 chars - %26
    string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);

    //Build the signing key
    string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
    EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));

    //Sign the request
    HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
    string oauthsignature = Convert.ToBase64String(
      hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));

    //Tell Twitter we don't do the 100 continue thing
    ServicePointManager.Expect100Continue = false;

    //authorization header
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);
    StringBuilder authorizationHeaderParams = new StringBuilder();
    authorizationHeaderParams.Append("OAuth ");
    authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
    authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
    authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
    authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
    if (!string.IsNullOrEmpty(oauthtoken))
        authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\",");
    authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
    authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
    webRequest.Headers.Add("Authorization", authorizationHeaderParams);

    webRequest.Method = "GET";
    webRequest.ContentType = "application/x-www-form-urlencoded";

    //Allow us a reasonable timeout in case Twitter's busy
    webRequest.Timeout = 3 * 60 * 1000;
    try
    {
        //Proxy settings
        webRequest.Proxy = new WebProxy("enter proxy details/address");
        HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
        Stream dataStream = webResponse.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
    }
}

我们可以 在此处 查看此 API 的描述。

public void SendReply()
{
    //If you want to reply to particular tweet then use @screenname along
    //with the status you need to update and status id of that particular
    //tweet to which you want to reply.
    //If you want to update status only then just post the message.
    string status = "@screenname Good day";
    string postBody = "status=" + Uri.EscapeDataString(status);
    string oauth_consumer_key = "your consumerkey";
    string oauth_consumerSecret = "your consumer secret";
    string oauth_signature_method = "HMAC-SHA1";
    string oauth_version = "1.0";
    string oauth_token = "your aouth token";
    string oauth_token_secret = "your oauth token secret";
    string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
    TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
    string oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
            
    SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
    //include the "in_reply_to_status_id" parameter if you need to reply to particular tweet.
    basestringParameters.Add("in_reply_to_status_id", 
      "status id of the post to which we are going to reply");
    basestringParameters.Add("status", Uri.EscapeDataString(status));
    basestringParameters.Add("oauth_version", oauth_version);
    basestringParameters.Add("oauth_consumer_key", oauth_consumer_key);
    basestringParameters.Add("oauth_nonce", oauth_nonce);
    basestringParameters.Add("oauth_signature_method", oauth_signature_method);
    basestringParameters.Add("oauth_timestamp", oauth_timestamp);
    if (!string.IsNullOrEmpty(oauth_token))
        basestringParameters.Add("oauth_token", oauth_token);

    //Build the signature string
    StringBuilder baseString = new StringBuilder();
    baseString.Append("POST" + "&");
    baseString.Append(EncodeCharacters(Uri.EscapeDataString("https://api.twitter.com/1.1/statuses/update.json") + "&"));
    foreach (KeyValuePair<string, string> entry in basestringParameters)
    {
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
    }

    //GS - Remove the trailing ambersand char, remember 
    //it's been urlEncoded so you have to remove the 
    //last 3 chars - %26
    string finalBaseString= baseString.ToString().Substring(0, baseString.Length - 3);

    //Build the signing key    
    string signingKey = EncodeCharacters(Uri.EscapeDataString(oauth_consumerSecret)) + "&" +
    EncodeCharacters(Uri.EscapeDataString(oauth_token_secret));

    //Sign the request
    HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
    string signatureString = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));

    //Tell Twitter we don't do the 100 continue thing
    ServicePointManager.Expect100Continue = false;

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(
      @"https://api.twitter.com/1.1/statuses/update.json?in_reply_to_status_id=status id");

    StringBuilder authorizationHeaderParams = new StringBuilder();
    authorizationHeaderParams.Append("OAuth ");
    authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauth_nonce) + "\",";)
    authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauth_signature_method) + "\",");
    authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauth_timestamp) + "\",");
    authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauth_consumer_key) + "\",");
    if (!string.IsNullOrEmpty(oauth_token))
      authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauth_token) + "\",");
    authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(signatureString) + "\",");
    authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauth_version) + "\"");
    webRequest.Headers.Add("Authorization", authorizationHeaderParams);

    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    Stream stream = webRequest.GetRequestStream();
    byte[] bodyBytes = new ASCIIEncoding().GetBytes(postBody);
    stream.Write(bodyBytes, 0, bodyBytes.Length);
    stream.Flush();
    stream.Close();

    //Allow us a reasonable timeout in case Twitter's busy
    webRequest.Timeout = 3 * 60 * 1000;
    try
    {
        webRequest.Proxy = new WebProxy("enter proxy details/address");
        HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
        Stream dataStream = webResponse.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex)
    {

    }
}

我们可以 在此处 查看此 API 的描述。

public void RequestToken()
{
    string oauthcallback = "your callback URL";
    string oauthconsumerkey = "your consumer key";
    string oauthconsumersecret = "your consumer secret";
    string oauthtokensecret = string.Empty;
    string oauthtoken = string.Empty;
    string oauthsignaturemethod = "HMAC-SHA1";
    string oauthversion = "1.0";
    string oauthnonce = 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 oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
    string url = "https://api.twitter.com/oauth/request_token?oauth_callback=" + oauthcallback;
    SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
    basestringParameters.Add("oauth_version", oauthversion);
    basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
    basestringParameters.Add("oauth_nonce", oauthnonce);
    basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
    basestringParameters.Add("oauth_timestamp", oauthtimestamp);
    basestringParameters.Add("oauth_callback", Uri.EscapeDataString(oauthcallback));

    //Build the signature string
    StringBuilder baseString = new StringBuilder();
    baseString.Append("POST" + "&");
    baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
    foreach (KeyValuePair<string, string> entry in basestringParameters)
    {
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
    }

    //Remove the trailing ambersand char last 3 chars - %26
    string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);

    //Build the signing key
    string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
    EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));

    //Sign the request
    HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
    string oauthsignature = Convert.ToBase64String(
      hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));

    //Tell Twitter we don't do the 100 continue thing
    ServicePointManager.Expect100Continue = false;
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);

    StringBuilder authorizationHeaderParams = new StringBuilder();
    authorizationHeaderParams.Append("OAuth ");
    authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
    authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
    authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
    authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
    authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
    authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
    webRequest.Headers.Add("Authorization", authorizationHeaderParams);

    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";

    //Allow us a reasonable timeout in case Twitter's busy
    webRequest.Timeout = 3 * 60 * 1000;

    try
    {
        webRequest.Proxy = new WebProxy("enter proxy details/address");
        HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
        Stream dataStream = webResponse.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
    }
}

我们可以 在此处 查看此 API 的描述。

public void Authorize()
{
    string oauthconsumerkey = "your consumer key";
    string oauthconsumersecret = "your consumer secret";
    string oauthtokensecret = 
      "Use the oauth_token_secret you receieved as the result of Request_Token API";
    string oauthsignaturemethod = "HMAC-SHA1";
    string oauthversion = "1.0";
    string oauthtoken = "Use the oauth_token you receieved as the result of Request_Token API";
    string url = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauthtoken;
    string oauthnonce = 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 oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
    SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
    basestringParameters.Add("oauth_version", oauthversion);
    basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
    basestringParameters.Add("oauth_nonce", oauthnonce);
    basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
    basestringParameters.Add("oauth_timestamp", oauthtimestamp);

    //Build the signature string
    StringBuilder baseString = new StringBuilder();
    baseString.Append("GET" + "&");
    baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
    foreach (KeyValuePair<string, string> entry in basestringParameters)
    {
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
    }

    //Remove the trailing ambersand char last 3 chars - %26
    string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);

    //Build the signing key
    string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
    EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));

    //Sign the request
    HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
    string oauthsignature = 
      Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));


    //Tell Twitter we don't do the 100 continue thing
    ServicePointManager.Expect100Continue = false;

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);

    StringBuilder authorizationHeaderParams = new StringBuilder();
    authorizationHeaderParams.Append("OAuth ");
    authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
    authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
    authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
    authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
    authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
    if (!string.IsNullOrEmpty(oauthtoken))
        authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\",");
    authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
    webRequest.Headers.Add("Authorization", authorizationHeaderParams);

    webRequest.Method = "GET";
    webRequest.ContentType = "application/x-www-form-urlencoded";

    //Allow us a reasonable timeout in case Twitter's busy
    webRequest.Timeout = 3 * 60 * 1000;
    try
    {
        webRequest.Proxy = new WebProxy("enter proxy details/address");
        HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
        Stream dataStream = webResponse.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
    }
}
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;
}                                                
  1. Verify_Credentials API:我们可以 在此处 查看此 API 的描述。
  2. Search API:我们可以 在此处 查看此 API 的描述。
  3. Statuses/Update API:我们可以 在此处 查看此 API 的描述。 
  4. Request_Token API:我们可以 在此处 查看此 API 的描述。
  5. Authorize API:我们可以 在此处 查看此 API 的描述。

实用技巧

检查 oauth 工具的基字符串。它提供了选项来检查代码生成的基字符串是否与工具生成的基字符串相同。如果相同,则一切正常,但如果代码生成的基字符串与工具的基字符串不同,则我们需要检查代码使其相等。

根据 OAuth Core 1.0,未保留字符集中的字符不得编码,其余字符必须编码。
未保留 = 字母、数字、-、.、_、~

参考文献

我没有足够的能力独立撰写这篇文章。因此,以下是参考列表: 

© . All rights reserved.