Click here to Skip to main content
15,868,127 members
Articles / Web Development / ASP.NET

Twitter API v1.1 with OAuth

Rate me:
Please Sign up or sign in to vote.
4.89/5 (39 votes)
2 Apr 2015CPOL3 min read 135.4K   62   53
Twitter API v1.1 with OAuth.

Introduction   

The OAuth protocol enables websites or applications (Consumers) to access Protected Resources from a web service (Service Provider) via an API, without requiring Users to disclose their Service Provider credentials to the Consumers. More generally, OAuth creates a freely-implementable and generic methodology for API authentication. 

OAuth aims to unify the experience and implementation of delegated web service authentication into a single, community-driven protocol. OAuth builds on existing protocols and best practices that have been independently implemented by various websites. An open standard, supported by large and small providers alike, promotes a consistent and trusted experience for both application developers and the users of those applications.

Recently twitter announced API v1.1 and also deprecated v1.0 API support.

In v1.1 twitter is very strict in terms of authentication. We need to create an application for accessing the Twitters API. 

OAuth_Authentication_Flow_v1.0

Application creation  

For creating an application we need to login with our twitters credentials on https://dev.twitter.com/.

After successfully logged-in click on "Create a new application" to create an application.

Image 2

After that fill the below shown form to create an application.

Provide Application name,description,website URL and call-back URL.
Image 3

 

Image 4

Accept the twitter mentioned rule and regulation and click on "Create your Twitter application" to proceed further and we will see the below screen.

Image 5

Now we have our Consumer Key and Consumer Secret  but we don't have any kind of Access Token and Access Token Secret.

So for generating/creating the access token and access token secret click on "Create Access Token" as shown in below image

Image 6

We will see below screen with the confirmation

Image 7

Cheers guys we have successfully created an application for Twitter.

Now its time to write some code for accessing Twitter API.

Using the code 

Twitter provides many API if we want we can check here.

We will look into code now.

C#
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)
    {
       
    }
}

We can have a look at the description of this API over here

C#
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)
    {
    }
}

We can have a look at the description of this API over here.

C#
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)
    {

    }
}

We can have a look at the description of this API over here.

C#
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)
    {
    }
}

We can have a look at the description of this API over here.

C#
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)
    {
    }
}
C#
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: We can have a look at the description of this API over https://dev.twitter.com/rest/reference/get/account/verify_credentials
  2. Search API: We can have a look at the description of this API over https://dev.twitter.com/rest/reference/get/search/tweets
  3. Statuses/Update API: We can have a look at the description of this API over https://dev.twitter.com/rest/reference/post/statuses/update
  4. Request_Token API: We can have a look at the description of this API over https://dev.twitter.com/oauth/reference/post/oauth/request_token
  5. Authorize API: We can have a look at the description of this API over https://dev.twitter.com/oauth/reference/get/oauth/authorize

Useful Trick

Check the oauth tool for the basestring.It gives us the option to check whether code generated basestring and tool generated basestring are same or not. If it is same then good to go but if code generated basestring is different from tool's basestring then we need to look at our code to make it equal.

As per OAuth Core 1.0, Characters in the unreserved character set MUST NOT be encoded and rest of the characters must be encoded.
unreserved = ALPHA, DIGIT, '-', '.', '_', '~'

Image 8

References

I am not smart enough to write this article on my own. So here is the list of references: 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
AnswerRe: Image Uploads Pin
Rajan Patekar24-Nov-14 4:20
professionalRajan Patekar24-Nov-14 4:20 
GeneralRe: Image Uploads Pin
RossGamble24-Nov-14 21:40
RossGamble24-Nov-14 21:40 
GeneralRe: Image Uploads Pin
Member 885514617-Dec-14 1:19
Member 885514617-Dec-14 1:19 
GeneralRe: Image Uploads Pin
Rajan Patekar22-Dec-14 4:07
professionalRajan Patekar22-Dec-14 4:07 
GeneralRe: Image Uploads Pin
Rajan Patekar29-Dec-14 4:23
professionalRajan Patekar29-Dec-14 4:23 
GeneralRe: Image Uploads Pin
RossGamble19-Jan-15 22:39
RossGamble19-Jan-15 22:39 
QuestionGetting 401 error when searching for multiple terms Pin
carl_sargunar14-Oct-14 11:47
carl_sargunar14-Oct-14 11:47 
AnswerRe: Getting 401 error when searching for multiple terms Pin
carl_sargunar19-Oct-14 14:47
carl_sargunar19-Oct-14 14:47 
In case anyone else gets stuck with this - I figured out after a LOT of experimenting that you need to escape your query in the signature method. I replaced the baseSteringPArameters dictionary with the below, where searchCritertia is the raw search string

C#
var basestringParameters = new SortedDictionary<string, string>
            {
                { "q", Uri.EscapeDataString(searchCriteria)},
                { "oauth_version", oauthversion },
                { "oauth_consumer_key", oauthconsumerkey },
                { "oauth_nonce", oauthnonce },
                { "oauth_signature_method", oauthsignaturemethod },
                { "oauth_timestamp", oauthtimestamp },
                { "oauth_token", oauthtoken }
            };

GeneralRe: Getting 401 error when searching for multiple terms Pin
Rajan Patekar21-Nov-14 17:36
professionalRajan Patekar21-Nov-14 17:36 
QuestionError - {"The remote server returned an error: (401) Unauthorized."} Pin
Simon Chia3-Oct-14 18:14
Simon Chia3-Oct-14 18:14 
AnswerRe: Error - {"The remote server returned an error: (401) Unauthorized."} Pin
Rajan Patekar7-Oct-14 4:49
professionalRajan Patekar7-Oct-14 4:49 
QuestionGetting 401 with RequestToken() Pin
RealComander2-May-14 11:22
RealComander2-May-14 11:22 
AnswerRe: Getting 401 with RequestToken() Pin
Rajan Patekar5-May-14 2:58
professionalRajan Patekar5-May-14 2:58 
GeneralRe: Getting 401 with RequestToken() Pin
dmid9-Jun-15 18:09
dmid9-Jun-15 18:09 
QuestionCan't post twitter comment from c# windows application, Pin
Sathish011731-Mar-14 21:23
Sathish011731-Mar-14 21:23 
AnswerRe: Can't post twitter comment from c# windows application, Pin
Rajan Patekar5-Apr-14 23:39
professionalRajan Patekar5-Apr-14 23:39 
Questionstupid question Pin
4554n21-Feb-14 14:25
4554n21-Feb-14 14:25 
AnswerRe: stupid question Pin
Rajan Patekar26-Feb-14 19:54
professionalRajan Patekar26-Feb-14 19:54 
GeneralRe: stupid question Pin
4554n27-Feb-14 2:07
4554n27-Feb-14 2:07 
GeneralRe: stupid question Pin
Rajan Patekar16-Mar-14 3:03
professionalRajan Patekar16-Mar-14 3:03 
GeneralRe: stupid question Pin
notclear4-Jun-14 23:52
notclear4-Jun-14 23:52 
GeneralRe: stupid question Pin
Rajan Patekar12-Jun-14 22:18
professionalRajan Patekar12-Jun-14 22:18 
Question401 error Pin
CodeArgie29-Jan-14 9:55
CodeArgie29-Jan-14 9:55 
AnswerRe: 401 error Pin
Rajan Patekar29-Jan-14 18:22
professionalRajan Patekar29-Jan-14 18:22 
GeneralRe: 401 error Pin
CodeArgie30-Jan-14 4:09
CodeArgie30-Jan-14 4:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.