You’ll need to register on https://developer.twitter.com and get the following details in order to be able to call the API:
Twitter_Access_Token
Twitter_Access_Secret
Twitter_API_Key
Twitter_API_Secret
The below URL is the end-point to get the users using the Twitter API:
https://api.twitter.com/1.1/users/search.json
You can do as many iterations to fetch the users and define the page size for each iteration. So, to fetch 100 users, do 5 iterations of page size 20:
int total_res = 0;
List<TUserResult> lst = new List<TUserResult>();
for (int i = 1; i <= 5; i++)
{
string q = Convert.ToString(query).Trim();
//code for performing oAuth request.
string res_url = "https://api.twitter.com/1.1/users/search.json";
//Fetch oauth application keys from the config file...
var oauth_token = ConfigurationManager.AppSettings["Twitter_Access_Token"];
var oauth_token_secret = ConfigurationManager.AppSettings["Twitter_Access_Secret"];
var oauth_consumer_key = ConfigurationManager.AppSettings["Twitter_API_Key"];
var oauth_consumer_secret = ConfigurationManager.AppSettings["Twitter_API_Secret"];
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
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();
// create oauth signature
var baseFormat = "count={0}&include_entities={1}&lang={2}&oauth_consumer_key={3}&oauth_nonce={4}&oauth_signature_method={5}" +
"&oauth_timestamp={6}&oauth_token={7}&oauth_version={8}&page={9}&q={10}";
var baseString = string.Format(baseFormat,
20.ToString(),
"false",
Uri.EscapeDataString("en,es,fr,de,it,pt,tr,ko,ru,ja"),
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
i.ToString(),
EscapeUriDataStringRfc3986(q)
);
baseString = string.Concat("GET&", Uri.EscapeDataString(res_url), "&", Uri.EscapeDataString(baseString));
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)));
}
// create the request 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)
);
ServicePointManager.Expect100Continue = false;
// make the request
var postBody = "count=20&include_entities=false&lang=" + Uri.EscapeDataString("en,es,fr,de,it,pt,tr,ko,ru,ja") + "&page=" + i.ToString() + "&q=" + EscapeUriDataStringRfc3986(q);
res_url += "?" + postBody;
//Make a WebRequest to the Twitter end-point:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(res_url);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var objText = reader.ReadToEnd();
try
{
JArray jsonDat = JArray.Parse(objText);
//ToDo: Compare the list of Ids from each iteration for duplicates.
//General Idea for iterating through the results in each iteration:
for (int x = 0; x < jsonDat.Count(); x++)
{
TUserResult twitter = new TUserResult();
twitter.name = jsonDat[x]["name"].ToString();
twitter.screen_name = jsonDat[x]["screen_name"].ToString();
twitter.description = jsonDat[x]["description"].ToString();
twitter.image_url = jsonDat[x]["profile_image_url_https"].ToString();
lst.Add(twitter);
}
total_res += jsonDat.Count();
if (jsonDat.Count() == 0 || jsonDat.Count() < 20)
{
break;
}
}
catch (Exception twit_error)
{
//Handle exceptions...
}
}
Here is the definition for EscapeUriDataStringRfc3986 method:
internal static string EscapeUriDataStringRfc3986(string value)
{
// Start with RFC 2396 escaping by calling the .NET method to do the work.
// This MAY sometimes exhibit RFC 3986 behavior (according to the documentation).
// If it does, the escaping we do that follows it will be a no-op since the
// characters we search for to replace can't possibly exist in the string.
StringBuilder escaped = new StringBuilder(Uri.EscapeDataString(value));
// Upgrade the escaping to RFC 3986, if necessary.
for (int i = 0; i < UriRfc3986CharsToEscape.Length; i++)
{
escaped.Replace(UriRfc3986CharsToEscape[i], Uri.HexEscape(UriRfc3986CharsToEscape[i][0]));
}
// Return the fully-RFC3986-escaped string.
return escaped.ToString();
}
Below are the Twitter user details classes defined:
public class TUserResult
{
public string name { get; set; }
public string screen_name { get; set; }
public string description { get; set; }
public string image_url { get; set; }
public string errors { get; set; }
}