WillShakes
WillShakes

Reputation: 11

Creating webrequest POST for Twitter API using VB.NET

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

Upvotes: 1

Views: 6569

Answers (1)

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

Upvotes: 4

Related Questions