gpt4 book ai didi

c# - 无法在 asp.net mvc 中实现将推文和图像一起发送到 twitter

转载 作者:太空宇宙 更新时间:2023-11-03 16:08:45 24 4
gpt4 key购买 nike

我正在开发 asp.net mvc。我正在尝试实现 twitter compose tweet 机制文本和图像,并将其作为 tweet 在 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 内部服务器错误。如果我的程序出错,请指导我。

最佳答案

我是 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

关于c# - 无法在 asp.net mvc 中实现将推文和图像一起发送到 twitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18276281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com