当我从C#代码调用yammer API时出现错误404

问题描述 投票:-1回答:1

我试图使用来自c#的Webrequest在yammer组中发布消息。这是我正在使用的代码

 request =(HttpWebRequest)WebRequest.Create("https://www.yammer.com/api/v1/messages.json");
    request.Method = "POST";     
    request.Headers.Add("Authorization", "Bearer abcdedsdgfggdhhh");             
    request.ContentType = "application/x-www-form-urlencoded";           
    string Data = "body=This is  demo msg send from Myapp&group_id=3027731&broadcast=true";              
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Data);      
    request.ContentLength = bytes.Length;       
    Stream requestStream = request.GetRequestStream();            
    requestStream.Write(bytes, 0,(int)request.ContentLength);            
    response = (HttpWebResponse)request.GetResponse();

运行此代码块后,它将400错误请求作为错误!有人可以帮我理解这段代码中的问题以及出了什么问题?

c# api post httpwebrequest yammer
1个回答
1
投票

您可以尝试使用以下包装方法在yammer上发布消息(请注意,此代码使用AuthAuthbase类:

public static string PostMessage(string body)
{
       NameValueCollection parameters = new NameValueCollection();
       parameters.Add("body", body);
       string response = string.Empty;
       response = Post("https://www.yammer.com/api/v1/messages/", parameters);
       return response;
}

public static string Post(string url, NameValueCollection parameters)
{
            string nonce, timestamp;
            string fullUrl = EncodeUrl(url, parameters);
            string signature = GetSignature(WebMethod.POST, fullUrl, out timestamp, out nonce);
            HttpWebRequest request = CreateWebRequest(url, WebMethod.POST, nonce, timestamp, signature);
int count = 0;
            string queryString = string.Empty;
            foreach (string key in parameters.Keys)
            {
                if (count == 0)
                    queryString = key + "=" + Rfc3986.Encode(parameters[key]);
                else
                    queryString += "&" + key + "=" + Rfc3986.Encode(parameters[key]);
                count++;
            }


            byte[] postDataBytes = Encoding.ASCII.GetBytes(queryString);
            request.ContentLength = postDataBytes.Length;
            Stream reqStream = request.GetRequestStream();
            reqStream.Write(postDataBytes, 0, postDataBytes.Length);
            reqStream.Close();

            WebResponse response = null;
            string data = string.Empty;
            try
            {
                response = request.GetResponse();
                data = response.Headers["Location"];
            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show("Error retrieving web response " + ex.Message);
                throw ex;
            }
            finally
            {
                if (response != null)
                    response.Close();
            }
            return data;
        }

        private static string EncodeUrl(string url, NameValueCollection parameters)
        {
            string fullUrl = string.Empty;
            int count = 0;
            foreach (string key in parameters.Keys)
            {
                if (count == 0)
                    fullUrl = url + "?" + key + "=" + Rfc3986.Encode(parameters[key].ToLower());
                else
                    fullUrl += "&" + key + "=" + Rfc3986.Encode(parameters[key].ToLower());
                count++;
            }
            return fullUrl;
        }


public static string GetSignature(WebMethod method, string url, out string timestamp, out string nonce)
        {
            OAuthBase oAuth = new OAuthBase();
            nonce = oAuth.GenerateNonce();
            timestamp = oAuth.GenerateTimeStamp();
            string nurl, nrp;

            Uri uri = new Uri(url);
            string sig = oAuth.GenerateSignature(
                uri,
                YOURCONSUMERKEY,
                YOURCONSUMER_SECRET,
                AuthToken,
                AuthTokenSecret,
                method.ToString(),
                timestamp,
                nonce,
                OAuthBase.SignatureTypes.PLAINTEXT, out nurl, out nrp);

            return System.Web.HttpUtility.UrlEncode(sig);
        }

private static HttpWebRequest CreateWebRequest(string fullUrl, WebMethod method, string nonce, string timeStamp, string sig)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUrl);
            request.Method = method.ToString();
            request.Proxy = Yammer.Session.WebProxy;
            string authHeader = CreateAuthHeader(method, nonce, timeStamp, sig);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Authorization", authHeader);
            return request;
        }

private static string CreateAuthHeader(WebMethod method, string nonce, string timeStamp, string sig)
{
            var sb = new StringBuilder();
            sb.Append("OAuth ");
            if (method == WebMethod.POST)
                sb.Append("realm=\"" + "\",");
            else
                sb.Append("realm=\"\",");

            string authHeader = "oauth_consumer_key=\"" + YOURCONSUMERKEY + "\"," +
                                "oauth_token=\"" + YOURAUTHTOKEN  + "\"," +
                                "oauth_nonce=\"" + nonce + "\"," +
                                "oauth_timestamp=\"" + timeStamp + "\"," +
                                "oauth_signature_method=\"" + "HMAC-SHA1" + "\"," +
                                "oauth_version=\"" + "1.0" + "\"," +
                                "oauth_signature=\"" + sig + "\"";

            sb.Append(authHeader);
            return sb.ToString();
}
© www.soinside.com 2019 - 2024. All rights reserved.