1

我正在尝试上传文件以及向 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 中 :)

4

1 回答 1

2

可以使用 MultipartFormDataContent 类型将二进制内容发布到 Yammer messages.json REST 端点。

一个发布许多图像、文本和标签的工作示例:

WebProxy proxy = new WebProxy()
{
    UseDefaultCredentials = true,
};
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
    Proxy = proxy,
};
using (var client = new HttpClient(httpClientHandler))
{
    using (var multipartFormDataContent = new MultipartFormDataContent())
    {
    string body = "Text body of message";
    var values = new[]
    {
        new KeyValuePair<string, string>("body", body),
        new KeyValuePair<string, string>("group_id", YammerGroupID),
        new KeyValuePair<string, string>("topic1", "Topic ABC"),
    };
    foreach (var keyValuePair in values)
    {
        multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
    }
    int i = 1;
    foreach (Picture p in PictureList)
    {
        var FileName = string.Format("{0}.{1}", p.PictureID.ToString("00000000"), "jpg");
        var FilePath = Server.MapPath(string.Format("~/images/{0}", FileName));
        if (System.IO.File.Exists(FilePath)) 
        {
            multipartFormDataContent.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(FilePath)), '"' + "attachment" + i.ToString() + '"', '"' + FileName + '"');
            i++;
        }
    }
    var requestUri = "https://www.yammer.com/api/v1/messages.json";
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
    var result = client.PostAsync(requestUri, multipartFormDataContent).Result;
     }
}
于 2016-11-22T05:07:03.233 回答