Https://api.twitter.com/1.1/statuses/update_with_media.json not working


#1

Hello Everyone,

I am posting image along with status. I have integrate code as per sample shown in this page https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media.

I receive always “The remote server returned an error: (403) Forbidden. ----> {“errors”:[{“code”:195,“message”:“Missing or invalid url parameter.”}]}” exception.

Can anyone have idea whats going wrong in below piece of code?


        Dim status As String = "test tweet with media"
        Dim imageFile As String = HttpContext.Current.Server.MapPath("test.png")

        Dim oauth_consumer_key As String = TwitterConsumerKey
        Dim oauth_consumerSecret As String = TwitterConsumerSecret
        Dim oauth_signature_method As String = "HMAC-SHA1"
        Dim oauth_version As String = "1.0"
        Dim oauth_token As String = TwitterAccessToken
        Dim oauth_token_secret As String = TwitterAccessTokenSecret

        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)


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


        baseString = baseString.Substring(0, baseString.Length - 3)


        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)))


        ServicePointManager.Expect100Continue = False

        Dim tweetRequest As HttpWebRequest = DirectCast(WebRequest.Create("https://api.twitter.com/1.1/statuses/update_with_media.json"), HttpWebRequest)
        tweetRequest.Method = "POST"
        tweetRequest.PreAuthenticate = True
        tweetRequest.AllowWriteStreamBuffering = True

        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) & """"
        tweetRequest.Headers.Add("Authorization", authorizationHeaderParams)


        Dim boundry As String = "------" & Guid.NewGuid().ToString().Replace("-", "") & "------"
        Dim separator As String = "=" & boundry
        Dim footer As String = Environment.NewLine & separator & "-" & Environment.NewLine
        Dim contentType As String = "image/png"
        Dim fileHeader As String = "Content-Disposition: form-data; name=""media""; filename=""" & Path.GetFileName(imageFile) & """"
        Dim encoding = System.Text.Encoding.GetEncoding("iso-8859-1")
        Dim contents = New System.Text.StringBuilder()

        contents.AppendLine(separator)
        contents.AppendLine("Content-Disposition: form-data; name=""status""")
        contents.AppendLine()
        contents.AppendLine(status)
        contents.AppendLine(separator)
        contents.AppendLine("Content-Type: image/png;name=""media""")
        contents.AppendLine(fileHeader)
        contents.AppendLine("Content-Location: media")
        contents.AppendLine()

        Using s = tweetRequest.GetRequestStream()

            Dim bytes As Byte() = encoding.GetBytes(contents.ToString())
            s.Write(bytes, 0, bytes.Length)


            bytes = File.ReadAllBytes(imageFile)
            s.Write(bytes, 0, bytes.Length)


            bytes = encoding.GetBytes(footer)
            s.Write(bytes, 0, bytes.Length)
        End Using

    
        tweetRequest.ContentType = "multipart/form-data; boundary=""" & boundry & """"

    
        tweetRequest.Timeout = 3 * 60 * 1000
        Try

            Dim webResponse As HttpWebResponse = TryCast(tweetRequest.GetResponse(), HttpWebResponse)
            Dim dataStream As Stream = webResponse.GetResponseStream()

            Dim reader As New StreamReader(dataStream)

            Dim responseFromServer As String = reader.ReadToEnd()

            Dim result As TwitterPostResponse = JsonConvert.DeserializeObject(Of TwitterPostResponse)(responseFromServer)

        Catch webex As WebException

            Dim exstream As StreamReader = New StreamReader(webex.Response.GetResponseStream())
            Dim exceptionString = exstream.ReadToEnd()
           
        Catch ex As Exception
           
        End Try


#2

Hello Everyone,

Any Idea whats going wrong?

Thanks


#3

Take a look at https://dev.twitter.com/docs/uploading-media for more details on uploading media. Note that the field name for media is ‘media[]’