Retrieving the twitter identity

By | April 14, 2017

In the previous article I showed how to use OAuth to connect to twitter. At this point all the authentication and authorization has been done and we are busy with the last step to retrieve the Identity information from twitter specifically.

Just for reference I am including the image of the components involved with Oauth.

The code below connects to twitter and retrieves the identity information in JSON format.

string oAuthProviderUri = “https://api.twitter.com”;
string identityRequestUri = oAuthProviderUri + “/1.1/account/verify_credentials.json”;
string authHeader = OAuthMan.GenerateAuthzHeader(identityRequestUri, “GET”);

Uri userCredentialUri = new Uri(identityRequestUri);

string userInfo = retrieveUserInformation(userCredentialUri, authHeader);

The following method reads the incoming response and returns a JSON string.

private string retrieveUserInformation(Uri uri, string authHeader)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = “GET”;
request.ServicePoint.Expect100Continue = false;
request.ContentType = “x-www-form-urlencoded”;

request.Headers[“Authorization”] = authHeader;

WebResponse response = null;
Stream receiveStream = null;
StringBuilder responseResult = new StringBuilder();
try
{
response = request.GetResponse();
try
{
receiveStream = response.GetResponseStream();

Encoding encode = System.Text.Encoding.GetEncoding(“utf-8”);
StreamReader readStream = new StreamReader(receiveStream, encode);
Char[] read = new Char[256];

// Reads 256 characters at a time.
int count = readStream.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
responseResult.Append(str);
count = readStream.Read(read, 0, 256);
}

return responseResult.ToString();
}
finally
{
receiveStream.Close();
}
}
finally
{
response.Close();
}
}

Next I decode the JSON and read it into a a more usable format.

dynamic jsonTwitterIdentity = Json.Decode(userInfo);

TwitterIdentity twitterIdentity = new TwitterIdentity();
twitterIdentity.Id = jsonTwitterIdentity.id;
twitterIdentity.Name = jsonTwitterIdentity.name;
twitterIdentity.Description = jsonTwitterIdentity.description;
twitterIdentity.ScreenName = jsonTwitterIdentity.screen_name;
twitterIdentity.Location = jsonTwitterIdentity.location;
twitterIdentity.Language = jsonTwitterIdentity.lang;

Leave a Reply

Your email address will not be published.