我正在研究 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。如果我的程序出错,请指导我。