本指南詳細介紹如何使用 OAuth 透過 Twitter API v1.1 進行身份驗證,並隨後透過 HttpWebRequest 檢索使用者的時間軸。 舊版 v1 API 已過時;此方法利用更新的協定。
OAuth 驗證步驟:
https://api.twitter.com/oauth2/token
的身份驗證請求。 請求標頭必須包含使用 Base64 編碼字串的消費者金鑰和秘密。 grant_type=client_credentials
.擷取使用者的時間軸:
https://api.twitter.com/1.1/statuses/user_timeline.json
提出請求。包含必要的查詢參數,例如 screen_name
、include_rts
、exclude_replies
和 count
。 程式碼範例(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>
請記得將佔位符替換為您的實際按鍵和螢幕名稱。 應添加錯誤處理和異常管理以供生產使用。 這個改進的範例闡明了變數命名並增強了可讀性。 您需要為 Newtonsoft.Json
安裝 JsonConvert
NuGet 軟體套件。
以上是如何使用 Twitter API v1.1 OAuth 進行驗證並使用 HttpWebRequest 檢索使用者的時間軸?的詳細內容。更多資訊請關注PHP中文網其他相關文章!