This guide details how to authenticate with the Twitter API v1.1 using OAuth and subsequently retrieve a user's timeline via HttpWebRequest. The legacy v1 API is obsolete; this method utilizes the updated protocol.
OAuth Authentication Steps:
https://api.twitter.com/oauth2/token
. The request header must include your consumer key and secret using a Base64 encoded string.grant_type=client_credentials
.Retrieving the User's Timeline:
https://api.twitter.com/1.1/statuses/user_timeline.json
. Include necessary query parameters such as screen_name
, include_rts
, exclude_replies
, and count
.Code Example (C#):
<code class="language-csharp">// Assume these variables are pre-populated: // oAuthConsumerKey: Your OAuth consumer key // oAuthConsumerSecret: Your OAuth consumer secret // screenname: The target Twitter username // Authentication string authHeaderFormat = "Basic {0}"; string authHeader = string.Format(authHeaderFormat, Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" + Uri.EscapeDataString(oAuthConsumerSecret)))); string postBody = "grant_type=client_credentials"; HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create("https://api.twitter.com/oauth2/token"); authRequest.Headers.Add("Authorization", authHeader); authRequest.Method = "POST"; authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (Stream stream = authRequest.GetRequestStream()) { byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody); stream.Write(content, 0, content.Length); } authRequest.Headers.Add("Accept-Encoding", "gzip"); HttpWebResponse authResponse = (HttpWebResponse)authRequest.GetResponse(); // Deserialize authentication response TwitterAuthResponse authResponseObject; using (authResponse) { using (StreamReader reader = new StreamReader(authResponse.GetResponseStream())) { string json = reader.ReadToEnd(); authResponseObject = JsonConvert.DeserializeObject<TwitterAuthResponse>(json); } } // Timeline Request string timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5"; string timelineUrl = string.Format(timelineFormat, screenname); HttpWebRequest timelineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl); string timelineHeaderFormat = "{0} {1}"; timelineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, authResponseObject.token_type, authResponseObject.access_token)); timelineRequest.Method = "GET"; HttpWebResponse timelineResponse = (HttpWebResponse)timelineRequest.GetResponse(); // Parse timeline response string timelineJson; using (timelineResponse) { using (StreamReader reader = new StreamReader(timelineResponse.GetResponseStream())) { timelineJson = reader.ReadToEnd(); } } // Process the timelineJson data.</code>
Remember to replace placeholders with your actual keys and screen name. Error handling and exception management should be added for production use. This improved example clarifies variable naming and enhances readability. You will need to have Newtonsoft.Json
NuGet package installed for JsonConvert
.
The above is the detailed content of How can I Authenticate with Twitter API v1.1 OAuth and Retrieve a User's Timeline using HttpWebRequest?. For more information, please follow other related articles on the PHP Chinese website!