2

我正在研究 asp.net mvc。我正在尝试实现 twitter 撰写推文机制文本以及图像并将其作为推文发送到 twitter。我遵循了twitter API 1.1提供的文档。我已经按照 Twitterizer 库完成了这个,但它向我抛出了错误,例如 API 版本 1 已被弃用,尽管我使用的是最新版本,并且它适用于除此之外的其余端点。所以我决定自己发出http请求

就我而言,我的表单中有文本区域和文件上传控件,例如,

<form method="post" action="/Home/Upload" enctype="multipart/form-data">
<textarea id="message" name="message"></textarea>
<input type="file" name="file"/>
<input type="submit" value="submit"/>
</form>

之后,在我的操作中,我得到了用户选择的图像和他在我的操作中输入的文本。我已将 HttpPostedPostedFileBase 转换为 byte[] 之类的,

[HttpPost]
        public ActionResult Upload(FormCollection coll, HttpPostedFileBase upfile)
        {

            byte[] data;
            using (Stream inputStream = upfile.InputStream)
            {
                MemoryStream memoryStream = inputStream as MemoryStream;
                if (memoryStream == null)
                {
                    memoryStream = new MemoryStream();
                    inputStream.CopyTo(memoryStream);
                }
                data = memoryStream.ToArray();
            }

            HttpWebRequest webRequest = WebRequest.Create("https://api.twitter.com/1.1/statuses/update_with_media.json") as HttpWebRequest;
            OAuthBase oauth = new OAuthBase();
            string nonce = oauth.GenerateNonce();
            string timeStamp = oauth.GenerateTimeStamp();
            string normalizedUrl;
            string normalizedRequestParameters;
            string sig = oauth.GenerateSignature
            (new System.Uri("https://api.twitter.com/1.1/statuses/update_with_media.json"), consumerKey, consumerSecret, userinfo.AuthToken,
            userinfo.PayUserId, "POST", timeStamp, nonce,
            OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl,
            out normalizedRequestParameters);
            string header = string.Format(@"OAuth oauth_consumer_key=""{0}"",oauth_signature_method=""{1}"",oauth_timestamp=""{2}"",oauth_nonce=""{3}"",oauth_version=""{4}"",oauth_token=""{5}"",oauth_signature=""{6}""",
            HttpUtility.UrlEncode(consumerKey), HttpUtility.UrlEncode("HMAC-SHA1"), HttpUtility.UrlEncode(timeStamp), HttpUtility.UrlEncode(nonce), HttpUtility.UrlEncode("1.0"), HttpUtility.UrlEncode(userinfo.AuthToken), HttpUtility.UrlEncode(sig));
            webRequest.Headers.Add("Authorization", header);
            webRequest.Method = "POST";
            webRequest.Credentials = CredentialCache.DefaultCredentials;
            ((HttpWebRequest)webRequest).UserAgent = ".NET Framework Example Client";
            Dictionary<string, object> fieldsToInclude = new Dictionary<string, object>();
            fieldsToInclude.Add("status", coll["new_message"]);
            fieldsToInclude.Add("media[]", data);
            string boundary = Guid.NewGuid().ToString().Replace("-", "");
            string dataBoundary = "--------------------r4nd0m";
            string contentType = "multipart/form-data; boundary=" + dataBoundary;
            byte[] mydata = GetMultipartFormData(fieldsToInclude, contentType);
            webRequest.ContentLength = mydata.Length;
            webRequest.ContentType = contentType;
            using (Stream requestStream = webRequest.GetRequestStream())
            {
                if (mydata != null)
                {
                    requestStream.Write(mydata, 0, mydata.Length);
                }
            }
            using (HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(webResponse.GetResponseStream());
                string retVal = reader.ReadToEnd();
            }        

            return View();
        }

在这里,我编写了一种为图像和文本数据准备多部分表单数据结构的方法,例如,

private byte[] GetMultipartFormData(Dictionary<string, object> fieldsToInclude, string boundary)
        {
            Stream formDataStream = new MemoryStream();
            Encoding encoding = Encoding.UTF8;          

            foreach (KeyValuePair<string, object> kvp in fieldsToInclude)
            {
                if (kvp.Value.GetType() == typeof(byte[]))
                {   //assume this to be a byte stream
                    byte[] data = (byte[])kvp.Value;

                    string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: application/octet-stream\r\n\r\n",
                        boundary,
                        kvp.Key,
                        kvp.Key);

                    byte[] headerBytes = encoding.GetBytes(header);

                    formDataStream.Write(headerBytes, 0, headerBytes.Length);
                    formDataStream.Write(data, 0, data.Length);


                }
                else
                {   //this is normal text data
                    string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
                        boundary,
                        kvp.Key,
                        kvp.Value);

                    byte[] headerBytes = encoding.GetBytes(header);

                    formDataStream.Write(headerBytes, 0, headerBytes.Length);
                }
            }

            string footer = string.Format("\r\n--{0}--\r\n", boundary);
            formDataStream.Write(encoding.GetBytes(footer), 0, footer.Length);
            formDataStream.Position = 0;
            byte[] returndata = new byte[formDataStream.Length];

            formDataStream.Read(returndata, 0, returndata.Length);
            formDataStream.Close();

            return returndata;
        }

这是我遵循 http 请求将图像上传到 twitter 的方式(也就是使用媒体上传)。但我收到错误500 Internal server error。如果我的程序出错,请指导我。

4

4 回答 4

1

我是 Tweetinvi 的开发者。上传就这么简单:

var imageBinary = File.ReadAllBytes("path");
var media = Upload.UploadImage(imageBinary);

var tweet = Tweet.PublishTweet("hello", new PublishTweetOptionalParameters
{
    Medias = { media }
});

我认为这可以为您节省很多时间。

用于上传的 Tweetinvi 文档:https ://github.com/linvi/tweetinvi/wiki/Upload

于 2016-05-24T11:29:50.497 回答
0

您可以在 LINQ to Twitter 中使用 TweetWithMedia 方法执行此操作,如下所示:

static void TweetWithMediaDemo(TwitterContext twitterCtx)
{
    string status = "Testing TweetWithMedia #Linq2Twitter " + DateTime.Now.ToString(CultureInfo.InvariantCulture);
    const bool possiblySensitive = false;
    const decimal latitude = StatusExtensions.NoCoordinate; //37.78215m;
    const decimal longitude = StatusExtensions.NoCoordinate; // -122.40060m;
    const bool displayCoordinates = false;

    const string replaceThisWithYourImageLocation = @"..\..\images\200xColor_2.png";

    var mediaItems =
        new List<Media>
        {
            new Media
            {
                Data = Utilities.GetFileBytes(replaceThisWithYourImageLocation),
                FileName = "200xColor_2.png",
                ContentType = MediaContentType.Png
            }
        };

    Status tweet = twitterCtx.TweetWithMedia(
        status, possiblySensitive, latitude, longitude, 
        null, displayCoordinates, mediaItems, null);

    Console.WriteLine("Media item sent - Tweet Text: " + tweet.Text);
}
于 2013-08-17T01:14:06.130 回答
0

最后我找到了方法,即 Twitterizer 类库中存在的问题。众所周知,Twitter API 已弃用 Twitter API 1.0,因此 Twitterizer 库根据 Twitter API 1.1 更新了所有 twitter api 端点,但它没有更新 update_status_media 端点。以至于我无法使用它。我从 github 获得了 Twitterizer2 库源代码。我已经检查了 update_status_media 端点方法并解决了这个问题。需要进行更改

Twitterizer2/Methods/Tweets/UpdateWithmediaCommand.cs 文件第 87 行更改行this.OptionalProperties.APIBaseAddress = " https://upload.twitter.com/1/ "; this.OptionalProperties.APIBaseAddress = " https://api.twitter.com/1.1/ "; 这条线。这很好用。在这里,我看到 Twitter API 1.1 文档中的语句说,

重要提示:在 API v1.1 中,您现在使用 api.twitter.com 作为域,而不是 upload.twitter.com。我们强烈建议在此方法中使用 SSL。

希望这些信息对大家有所帮助。

于 2013-08-20T08:24:24.443 回答
0

我们可以通过将图像作为流传递来使用 SendTweetWithMedia() 方法共享图像。为了将图像作为流发送,我们需要对其进行转换。

private void sharetwitter ()
{
          var oauth_consumer_key = "your API key";
          var oauth_consumer_secret = "Your API secret key";
          string token = "access token";
          string tokenSecret = "access token secret ";
          var post = db.Posts.Where(p => p.PostId ==id).FirstOrDefault();
          StringBuilder str = new StringBuilder();
          str.AppendLine(post.Title.Trim());
          str.AppendLine("learn .net a lot of helpful programming stuffs.");
          var service = new TweetSharp.TwitterService(oauth_consumer_key,oauth_consumer_secret);
          service.AuthenticateWith(token, tokenSecret);
          string url = "http://www.infinetsoft.com/Images/logoinfi.png";
          service.SendTweetWithMedia(new SendTweetWithMediaOptions
          {
               Status = str.ToString(),
               Images = new Dictionary<string, Stream> { { "infinetsoft", urltostream(url) } }
           });
         TempData["SuccessMessage"] = "tweeted success";
}

在这里我找到了更多细节的解决方案http://www.infinetsoft.com/Post/How-to-share-image-to-twitter-post-using-asp-net-MVC/1236#.V0Lj1DV97cs

于 2016-05-23T11:08:36.323 回答