401 Unauthorized, I can't solve it. Help please


#1

I copied and pasted some code that I found, modified it to some degree. Any help would be appreciated. Thanks.

    Public Sub Tweet(ByVal strText As String)
        Dim status As String = strText
        Dim postBody As String = "status=" & Uri.EscapeDataString(status)
        Dim oauth_token = ""
        Dim oauth_token_secret = ""
        Dim oauth_consumer_key = ""
        Dim oauth_consumerSecret = ""
        Dim oauth_signature_method As String = "HMAC-SHA1"
        Dim oauth_version As String = "1.0"
        Dim oauth_nonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
        Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0)
        Dim oauth_timestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()

        Dim basestringParameters As New SortedDictionary(Of String, String)()
        basestringParameters.Add("oauth_version", oauth_version)
        basestringParameters.Add("oauth_consumer_key", oauth_consumer_key)
        basestringParameters.Add("oauth_nonce", oauth_nonce)
        basestringParameters.Add("oauth_signature_method", oauth_signature_method)
        basestringParameters.Add("oauth_timestamp", oauth_timestamp)
        basestringParameters.Add("oauth_token", oauth_token)
        basestringParameters.Add("status", Uri.EscapeDataString(status))

        Dim baseString As String = [String].Empty
        baseString += "POST" & "&"
        baseString += Uri.EscapeDataString("https://api.twitter.com/1.1/statuses/update.json") & "&"
        For Each entry As KeyValuePair(Of String, String) In basestringParameters
            baseString += Uri.EscapeDataString(entry.Key + "=" + entry.Value & "&")
        Next

        'GS - Remove the trailing ambersand char, remember 
        'it's been urlEncoded so you have to remove the 
        'last 3 chars - %26
        baseString = baseString.Substring(0, baseString.Length - 3)

        'Build the signing key    
        Dim signingKey As String = Uri.EscapeDataString(oauth_consumerSecret) & "&" & Uri.EscapeDataString(oauth_token_secret)

        Dim hasher As New HMACSHA1(New ASCIIEncoding().GetBytes(signingKey))
        Dim signatureString As String = Convert.ToBase64String(hasher.ComputeHash(New ASCIIEncoding().GetBytes(baseString)))

        'Tell Twitter we don't do the 100 continue thing
        ServicePointManager.Expect100Continue = False

        Dim webRequest__1 As HttpWebRequest = DirectCast(WebRequest.Create("https://api.twitter.com/1.1/statuses/update.json?in_reply_to_status_id=status id"), HttpWebRequest)

        Dim authorizationHeaderParams As String = [String].Empty
        authorizationHeaderParams += "OAuth "
        authorizationHeaderParams += "oauth_nonce=" & """" & Uri.EscapeDataString(oauth_nonce) & ""","
        authorizationHeaderParams += "oauth_signature_method=" & """" & Uri.EscapeDataString(oauth_signature_method) & ""","
        authorizationHeaderParams += "oauth_timestamp=" & """" & Uri.EscapeDataString(oauth_timestamp) & ""","
        authorizationHeaderParams += "oauth_consumer_key=" & """" & Uri.EscapeDataString(oauth_consumer_key) & ""","
        authorizationHeaderParams += "oauth_token=" & """" & Uri.EscapeDataString(oauth_token) & ""","
        authorizationHeaderParams += "oauth_signature=" & """" & Uri.EscapeDataString(signatureString) & ""","
        authorizationHeaderParams += "oauth_version=" & """" & Uri.EscapeDataString(oauth_version) & """"
        webRequest__1.Headers.Add("Authorization", authorizationHeaderParams)

        webRequest__1.Method = "POST"
        webRequest__1.ContentType = "application/x-www-form-urlencoded"
        Dim stream As Stream = webRequest__1.GetRequestStream()
        Dim bodyBytes As Byte() = New ASCIIEncoding().GetBytes(postBody)
        stream.Write(bodyBytes, 0, bodyBytes.Length)
        stream.Flush()
        stream.Close()

        'Allow us a reasonable timeout in case Twitter's busy
        webRequest__1.Timeout = 3 * 60 * 1000
        Try
            Dim webResponse As HttpWebResponse = TryCast(webRequest__1.GetResponse(), HttpWebResponse)
            Dim dataStream As Stream = webResponse.GetResponseStream()
            Dim reader As New StreamReader(dataStream)
            Dim responseFromServer As String = reader.ReadToEnd()

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

#2

لا اله الا الله محمد رسول الله


#3

اللهم صل على محمد وعلى اله وصحبه اجمعين


#4

After some hair pulling, I found the solution that worked for me, and it’s two-fold:

  1. To properly set the $oauth_timestamp:
    $culture = New-Object System.Globalization.CultureInfo(“en-US”)
    $ts = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact(“01/01/1970”, “dd/MM/yyyy”, $culture);
    $oauth_timestamp = [System.Convert]::ToInt64($ts.TotalSeconds).ToString();

  2. Then - you have to remember it won’t retweet the same test message if you run it again after it works - so add a date/time (get-date) to your tweet string, and voila - repeated tests that work fine for me…finally.

Good luck - a generic 401 error is tough and frustrating to resolve when there are alot of moving parts.