使用 VB.NET 为 Twitter API 创建 Web 请求 POST

发布于 2025-01-07 15:13:42 字数 3774 浏览 1 评论 0原文

有不少 Twitter API 相关的帖子,但似乎没有一个能直接回答我的问题。

我知道如何以 POST 方式发送 HttpWebRequest。

我相当确定我需要将网络请求发送到:“https://api.twitter.com/1/statuses/update.json”(不完全清楚)

我知道有很多库,您所要做的就是是传递您的消费者密钥和令牌密钥。但是,我需要在函数中创建一些非常短的代码,简单地将硬编码字符串发布到 Twitter。当我开始工作时,硬编码字符串将被变量替换。

我不需要从 Twitter 获取状态更新或任何类型的信息。只需发布“你好世界!”首先,我可以从那里开始。

我被迫使用VB.NET。我正在使用 Visual Studio Web Developer 2010。

现在,总而言之,我已经在此处查看了 Nikolas Tarzia 的 C-Sharp 代码的 VB.NET 端口: http://oauth.googlecode.com/svn/code/vbnet/oAuth.vb

我可以通过查看这些函数大致了解它们的作用,但不知道我需要调用哪些函数来创建网络响应并将其发送到 Twitter!我也相信这段代码包含的内容超出了我的需要。如果我只想创建一个 POST,那么我可能只需要哈希函数和随机数函数以及我的令牌和密钥。是这样吗?如果是这样,有人可以帮我缩小范围吗?在此过程中,帮助我更好地理解需要将哪些正确形成的网络请求发送到 Twitter 才能快速发布推文?

谢谢,

Will

PS - 我最终根据查看 OAuth 文档、在 VB 中使用 POST 请求的简洁小代码示例以及 Twitter 开发人员区域 OAuth 工具为请求生成一些基本字符串,整理了一些代码。不幸的是,虽然它编译和运行正常,但我没有收到推文。有人可以看一下代码并看看是否可以发现任何明显的问题吗?显然,我用“xxxxx”替换了我的令牌和消费者密钥。圣诞节我想要的就是运行这段代码并在我的 Twitter 帐户上快速发一条推文! ;)

Public Shared Function Tweet(strText As String) As Boolean
        Dim boolResult As Boolean = False
        Dim urlAddress As Uri = New Uri("https://api.twitter.com/1/statuses/update.json")
        Dim strData As StringBuilder
        Dim byteData() As Byte
        Dim postStream As Stream = Nothing

        Dim strConsumerKey As String = "xxxxxx"
        Dim strConsumerSecret As String = "xxxxxx"
        Dim strAccessToken As String = "xxxxxx"
        Dim strAccessTokenSecret As String = "xxxxxx"

        Dim objRequest As HttpWebRequest
        Dim objResponse As HttpWebResponse = Nothing
        Dim objReader As StreamReader
        Dim objHeader As HttpRequestHeader = HttpRequestHeader.Authorization

        Try
            objRequest = DirectCast(WebRequest.Create(urlAddress), HttpWebRequest)

            objRequest.Method = "POST"
            objRequest.ContentType = "application/x-www-form-urlencoded"

            strData = New StringBuilder()
            strData.Append("&Hello_World%2521%3D%26oauth_consumer_key%3D" + strConsumerKey + "%26oauth_nonce%3Dda6bb8ce7e48547692f4854833afa680%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1329746260%26oauth_token%3D" + strAccessToken + "%26oauth_version%3D1.0")
            objRequest.Headers.Add(objHeader, "Authorization: OAuth oauth_consumer_key=""xxxx"", oauth_nonce=""da6bb8ce7e48547692f4854833afa680"", oauth_signature=""xxxx"", oauth_signature_method=""HMAC-SHA1"", oauth_timestamp=""1329750426"", oauth_token=""xxxx"", oauth_version=""1.0""")



            ' Create a byte array of the data we want to send  
            byteData = UTF8Encoding.UTF8.GetBytes(strData.ToString())

            ' Set the content length in the request headers  
            objRequest.ContentLength = byteData.Length

            Try
                postStream = objRequest.GetRequestStream()
                postStream.Write(byteData, 0, byteData.Length)
            Finally
                If Not postStream Is Nothing Then postStream.Close()
            End Try

            boolResult = True
        Catch ex As Exception
            boolResult = False
            HttpContext.Current.Session.Add("Error", ex.ToString())
        End Try

        Try
            ' Get response  
            objResponse = DirectCast(objRequest.GetResponse(), HttpWebResponse)

            ' Get the response stream into a reader  
            objReader = New StreamReader(objResponse.GetResponseStream())

            ' Console application output  
            Console.WriteLine(objReader.ReadToEnd())
        Finally
            If Not objResponse Is Nothing Then objResponse.Close()
        End Try

        Return boolResult
    End Function

There are quite a few Twitter API related posts, but none seem to answer my questions directly.

I know how to send an HttpWebRequest as POST.

I am fairly sure I need to send the webrequest to: "https://api.twitter.com/1/statuses/update.json" (not totally clear)

I know there are many libraries out there that all you have to do is pass your consumer keys and token keys. However, I need to create some very short code, in a function, that simple posts a hard coded string to Twitter. When I get this working that hard coded string will be replaced by variable.

I've no need to status updates or any kind of information from Twitter. Just POST "Hello World!" to start with, and I can go from there.

I am forced to use VB.NET. I am using Visual Studio Web Developer 2010.

Now, that all said, I have looked at Nikolas Tarzia's VB.NET port of C-Sharp code here:
http://oauth.googlecode.com/svn/code/vbnet/oAuth.vb

I can see roughly what the functions do by looking at them, but have no idea which ones I need to call to create a webresponse and send to Twitter! Also I believe this code contains more than I need. If I just want to create a POST, then likely I only need to hash function and the nonce function and my tokens and keys. Is that right? If so, could someone please help me narrow this down? In the process helping me understand a bit better what properly formed webrequest needs to be sent to Twitter to make a quick Tweet?

Thanks,

Will

PS - I finally put together some code, based on looking at OAuth documentation, a neat little code example on using POST request in VB, and the Twitter Developer area OAuth tool to generate some Base String for the request. Unfortunately while it compiles and runs okay, I am not getting a tweet. Could someone have a look at the code and see if they can spot any glaring issues? Obviously I replaced my tokens and consumer keys with "xxxxx". All I want for Christmas is to run this code and make a quick Tweet on my Twitter account! ;)

Public Shared Function Tweet(strText As String) As Boolean
        Dim boolResult As Boolean = False
        Dim urlAddress As Uri = New Uri("https://api.twitter.com/1/statuses/update.json")
        Dim strData As StringBuilder
        Dim byteData() As Byte
        Dim postStream As Stream = Nothing

        Dim strConsumerKey As String = "xxxxxx"
        Dim strConsumerSecret As String = "xxxxxx"
        Dim strAccessToken As String = "xxxxxx"
        Dim strAccessTokenSecret As String = "xxxxxx"

        Dim objRequest As HttpWebRequest
        Dim objResponse As HttpWebResponse = Nothing
        Dim objReader As StreamReader
        Dim objHeader As HttpRequestHeader = HttpRequestHeader.Authorization

        Try
            objRequest = DirectCast(WebRequest.Create(urlAddress), HttpWebRequest)

            objRequest.Method = "POST"
            objRequest.ContentType = "application/x-www-form-urlencoded"

            strData = New StringBuilder()
            strData.Append("&Hello_World%2521%3D%26oauth_consumer_key%3D" + strConsumerKey + "%26oauth_nonce%3Dda6bb8ce7e48547692f4854833afa680%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1329746260%26oauth_token%3D" + strAccessToken + "%26oauth_version%3D1.0")
            objRequest.Headers.Add(objHeader, "Authorization: OAuth oauth_consumer_key=""xxxx"", oauth_nonce=""da6bb8ce7e48547692f4854833afa680"", oauth_signature=""xxxx"", oauth_signature_method=""HMAC-SHA1"", oauth_timestamp=""1329750426"", oauth_token=""xxxx"", oauth_version=""1.0""")



            ' Create a byte array of the data we want to send  
            byteData = UTF8Encoding.UTF8.GetBytes(strData.ToString())

            ' Set the content length in the request headers  
            objRequest.ContentLength = byteData.Length

            Try
                postStream = objRequest.GetRequestStream()
                postStream.Write(byteData, 0, byteData.Length)
            Finally
                If Not postStream Is Nothing Then postStream.Close()
            End Try

            boolResult = True
        Catch ex As Exception
            boolResult = False
            HttpContext.Current.Session.Add("Error", ex.ToString())
        End Try

        Try
            ' Get response  
            objResponse = DirectCast(objRequest.GetResponse(), HttpWebResponse)

            ' Get the response stream into a reader  
            objReader = New StreamReader(objResponse.GetResponseStream())

            ' Console application output  
            Console.WriteLine(objReader.ReadToEnd())
        Finally
            If Not objResponse Is Nothing Then objResponse.Close()
        End Try

        Return boolResult
    End Function

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吖咩 2025-01-14 15:13:42

我已经使用 API1.1 将此类发布在 Twitter 上。
它需要构造函数中的 oauth 令牌、oauth 令牌秘密、oauth“消费者”密钥(这意味着 API 密钥)和 oauth 消费者秘密(这意味着 API 秘密)。如果您想在自己的帐户中发帖,这四个值将位于应用程序的 API 密钥选项卡中的 https:// apps.twitter.com/。如果您想在访客帐户上发帖,则必须创建一些额外的代码以将其重定向到 Twitter 进行登录并获取访问令牌。

Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text
Imports System.Security.Cryptography
Imports System.Net
Imports System.IO
Public Class SBTwitter

Private oauth_token As String
Private oauth_token_secret As String
Private oauth_consumer_key As String
Private oauth_consumer_secret As String

Public Sub New(ByVal APIKey As String, ByVal APISecret As String, ByVal oauthToken As String, ByVal oauthTokenSecret As String)
    oauth_token = oauthToken
    oauth_token_secret = oauthTokenSecret
    oauth_consumer_key = APIKey
    oauth_consumer_secret = APISecret
End Sub

Public Function PostInTwitter(ByVal post As String) As String
    Try
        Dim oauth_version = "1.0"
        Dim oauth_signature_method = "HMAC-SHA1"
        Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
        Dim timeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, _
         0, DateTimeKind.Utc)
        Dim oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
        Dim resource_url = "https://api.twitter.com/1.1/statuses/update.json"
        Dim status = post
        Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" & "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}"

        Dim baseString = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, _
         oauth_version, Uri.EscapeDataString(status))

        baseString = String.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString))
        Dim compositeKey = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))

        Dim oauth_signature As String
        Using hasher As New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
            oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
        End Using
        Dim 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}"""

        Dim 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))
        Dim postBody = "status=" & Uri.EscapeDataString(status)

        ServicePointManager.Expect100Continue = False

        Dim request As HttpWebRequest = DirectCast(WebRequest.Create(resource_url), HttpWebRequest)
        request.Headers.Add("Authorization", authHeader)
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        Using stream As Stream = request.GetRequestStream()
            Dim content As Byte() = ASCIIEncoding.ASCII.GetBytes(postBody)
            stream.Write(content, 0, content.Length)
        End Using
        Dim response As WebResponse = request.GetResponse()
        Return response.ToString
    Catch ex As Exception
        Return ex.Message
    End Try
End Function
End Class

I´ve made this class to post in twitter using API1.1.
It expects the oauth token, oauth token secret, oauth "consumer" key (this means API key) and oauth consumer secret (this means API secret) in the constructor. If you want to post in your own account, the four values will be in the API keys tab of your application in https://apps.twitter.com/. If you want to post on your visitors account you'll have to create some extra code to redirect them to twitter for login and get the access token.

Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text
Imports System.Security.Cryptography
Imports System.Net
Imports System.IO
Public Class SBTwitter

Private oauth_token As String
Private oauth_token_secret As String
Private oauth_consumer_key As String
Private oauth_consumer_secret As String

Public Sub New(ByVal APIKey As String, ByVal APISecret As String, ByVal oauthToken As String, ByVal oauthTokenSecret As String)
    oauth_token = oauthToken
    oauth_token_secret = oauthTokenSecret
    oauth_consumer_key = APIKey
    oauth_consumer_secret = APISecret
End Sub

Public Function PostInTwitter(ByVal post As String) As String
    Try
        Dim oauth_version = "1.0"
        Dim oauth_signature_method = "HMAC-SHA1"
        Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
        Dim timeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, _
         0, DateTimeKind.Utc)
        Dim oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
        Dim resource_url = "https://api.twitter.com/1.1/statuses/update.json"
        Dim status = post
        Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" & "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}"

        Dim baseString = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, _
         oauth_version, Uri.EscapeDataString(status))

        baseString = String.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString))
        Dim compositeKey = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))

        Dim oauth_signature As String
        Using hasher As New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
            oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
        End Using
        Dim 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}"""

        Dim 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))
        Dim postBody = "status=" & Uri.EscapeDataString(status)

        ServicePointManager.Expect100Continue = False

        Dim request As HttpWebRequest = DirectCast(WebRequest.Create(resource_url), HttpWebRequest)
        request.Headers.Add("Authorization", authHeader)
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        Using stream As Stream = request.GetRequestStream()
            Dim content As Byte() = ASCIIEncoding.ASCII.GetBytes(postBody)
            stream.Write(content, 0, content.Length)
        End Using
        Dim response As WebResponse = request.GetResponse()
        Return response.ToString
    Catch ex As Exception
        Return ex.Message
    End Try
End Function
End Class
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文