我正在尝试上传文件以及向 Yammer 发布一些消息。发布消息有效(所有授权内容等都可以)。当我想附加文件时出现问题。我试图从这里遵循代码:Yammer.Net
但我担心我遗漏了一些部分(无法引用整个项目,不知何故我的 Visual Studio 有问题)。
这就是为什么我尝试遵循指定请求参数的传统方式。下面我提出我的方法:
public bool postMessage(string body, string attachement)
{
var url = "https://www.yammer.com/api/v1/messages.json";
NameValueCollection parameters = new NameValueCollection();
parameters.Add("body", body);
parameters.Add("group_id", group_id);
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
//new request
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
request.Headers.Add("Authorization", authzHeader);
request.Method = "POST";
//content type settings
request.ContentType = "multipart/form-data";
request.KeepAlive = true;
//Proxy settings
request.Proxy = new System.Net.WebProxy("my company's proxy", true);
request.Proxy.Credentials = new System.Net.NetworkCredential(user, password);
//prepare the parameters
FileInfo fi = new FileInfo(attachement);
int i = 0;
long postDataSize = fi.Length;
parameters.Add("attachment", "attachment1");
parameters.Add("file", Path.GetFileName(attachement));
int count = 0;
string wdata = string.Empty;
foreach (string key in parameters.Keys)
{
if (count == 0)
{
wdata = key + "=" + oauth.encode(parameters[key]);
}
else
{
wdata += "&" + key + "=" + oauth.encode(parameters[key]);
}
count++;
}
//add the parameters
byte[] postDataBytes = Encoding.ASCII.GetBytes(wdata);
request.ContentLength = postDataBytes.Length + postDataSize;
Stream reqStream = request.GetRequestStream();
reqStream.Write(postDataBytes, 0, postDataBytes.Length);
//write the file
//postDataBytes = Encoding.ASCII.GetBytes(fileHeader);
//reqStream.Write(postDataBytes, 0, postDataBytes.Length);
int bufferSize = 10240;
FileStream readIn = new FileStream(attachement, FileMode.Open, FileAccess.Read);
readIn.Seek(0, SeekOrigin.Begin); // move to the start of the file
byte[] fileData = new byte[bufferSize];
int bytes;
while ((bytes = readIn.Read(fileData, 0, bufferSize)) > 0)
{
// read the file data and send a chunk at a time
reqStream.Write(fileData, 0, bytes);
}
readIn.Close();
reqStream.Close();
using (var response = (System.Net.HttpWebResponse)request.GetResponse())
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
string resp = reader.ReadToEnd();
return true;
}
}
}
代码可能看起来有点混乱,但我希望你能明白。主要问题是:
- 当我只发布一条消息(group_id,body)时,它可以工作。
- 当我尝试上述方法并发布附件时,我从 Yammer 收到“内部服务器错误”。
有谁知道如何使用 API 将文件上传到 Yammer?最好在 .NET 中 :)