使用API​​ 1.1的推文突然在2014年1月无效 - SSL / TLS

时间:2014-01-30 11:44:54

标签: .net twitter

这实际上是半个问题,一半是为了帮助处于同样困境的其他人。

我们的ASP.NET应用程序一直在以编程方式快速发送奇怪的推文(最近的危机是Twitter将其API从1.0更改为1.1)。我希望能够做的就是发送推文,我想尽可能少地学习OAuth。

我从原来的excellent page获得了原始的C#代码,用于在API 1.1中发送推文。当它停止工作时,我将代码转换为VB,所以我现在有一个类在这里被复制,以防任何人发现这个有用。以下是您可以称之为此课程的方式:

Dim tweet As New clsTweetVb

    Try
        tweet.Send(Message, ConsumerKey, ConsumerKeySecret, AccessToken, AccessTokenSecret)
    Catch
        ErrorMessage = tweet.ErrorMessage
    End Try

该类本身如下(抱歉格式化 - 我无法让StackOverflow正确粘贴代码):

Imports Microsoft.VisualBasic

进口系统 Imports System.Collections.Generic 进口System.Linq 导入System.Text 进口System.Net 进口System.IO 进口System.Security.Cryptography 公共类clsTweetVb

'from http//'www.overpie.com/aspnet/articles/csharp-post-message-to-twitter.cshtml then translated into VB by Wise Owl
Public IfWorked As Boolean = False
Public ErrorMessage As String = ""

'the message to send
Public Sub Send(message As String, oauth_consumer_key As String, oauth_consumer_secret As String, oauth_token As String,
         oauth_token_secret As String)

    'The JSON url to update the status
    Dim twitterUrl As String = "http://api.twitter.com/1.1/statuses/update.json"

    'set the oauth version and signature method
    Dim oauth_version As String = "1.0"
    Dim oauth_signature_method As String = "HMAC-SHA1"

    Dim oauth_nonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
    Dim tspan As TimeSpan = (DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc))
    Dim oauth_timestamp As String = Convert.ToInt64(tspan.TotalSeconds).ToString()

    'create oauth signature
    Dim baseFormat As String = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}"

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

    Dim oauth_signature As String = Nothing
    Using hasher As HMACSHA1 = New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(Uri.EscapeDataString(oauth_consumer_secret) & "&" & Uri.EscapeDataString(oauth_token_secret)))
        oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes("POST&" + Uri.EscapeDataString(twitterUrl) + "&" + Uri.EscapeDataString(baseString))))
    End Using

    'create the request header
    Dim authorizationFormat As String = "OAuth oauth_consumer_key=""{0}"", oauth_nonce=""{1}"", " &
        "oauth_signature=""{2}"", oauth_signature_method=""{3}"", " &
        "oauth_timestamp=""{4}"", oauth_token=""{5}"", " & "oauth_version=""{6}"""

    Dim authorizationHeader As String = String.Format(
            authorizationFormat,
            Uri.EscapeDataString(oauth_consumer_key),
            Uri.EscapeDataString(oauth_nonce),
            Uri.EscapeDataString(oauth_signature),
            Uri.EscapeDataString(oauth_signature_method),
            Uri.EscapeDataString(oauth_timestamp),
            Uri.EscapeDataString(oauth_token),
            Uri.EscapeDataString(oauth_version)
        )

    Dim objHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(twitterUrl), HttpWebRequest)
    objHttpWebRequest.Headers.Add("Authorization", authorizationHeader)
    objHttpWebRequest.Method = "POST"
    objHttpWebRequest.ContentType = "application/x-www-form-urlencoded"
    Using objStream As Stream = objHttpWebRequest.GetRequestStream()
        Dim content As Byte() = ASCIIEncoding.ASCII.GetBytes("status=" + Uri.EscapeDataString(message))
        objStream.Write(content, 0, content.Length)
    End Using

    Dim responseResult As String = ""

    ErrorMessage = "No error"
    Try

        'success posting
        Dim objWebResponse As WebResponse = objHttpWebRequest.GetResponse()
        Dim objStreamReader As StreamReader = New StreamReader(objWebResponse.GetResponseStream())
        responseResult = objStreamReader.ReadToEnd().ToString()

        IfWorked = True

    Catch EX As Exception

        'throw exception error
        responseResult = "Twitter Post Error: " + EX.Message.ToString() + ", authHeader: " + authorizationHeader
        ErrorMessage = responseResult
        IfWorked = False
    End Try

End Sub

结束班

当我尝试发推文时,我现在收到消息远程服务器返回错误:(403)禁止。我的问题是:我能否轻松解决这个问题,因为我认为这个问题是由Twitter tightening their security造成的?一个理想的解决方案可以解释我需要做什么而不必过多理解!感谢。

1 个答案:

答案 0 :(得分:1)

也许一个简单的解决方案可以使用TweetSharp API。我已经使用了一段时间了,发布推文,删除推文,阅读推文,获取大量有关账户的信息非常简单......

例如发布推文:(我有一个名为'Obj_Twitter'的对象,其中包含consumer_key对和Access_token对)

Function post_Status(obj As Obj_Twitter, mess As String) As String

        Dim service As TwitterService = New TwitterService(obj.consumer_key, obj.consumer_secret)
        service.AuthenticateWith(obj.access_token, obj.access_token_secret)

        Dim options As SendTweetOptions = New SendTweetOptions()
        options.Status = mess

        Dim twreturn As TweetSharp.TwitterStatus = service.SendTweet(options)

        Return twreturn.IdStr
    End Function

(可以在Visual Studio中找到Nuget包)

只有'问题'是该项目不再由其创建者积极开发。但它为我做了伎俩,也许它可以帮助你。