Yammer API - 附件上传

时间:2012-03-22 14:09:42

标签: c# yammer

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

1 个答案:

答案 0 :(得分:0)

可以使用MultipartFormDataContent类型将二进制内容POST到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;
     }
}