如何使用Twitter rest API发布直接消息

时间:2015-07-01 09:31:19

标签: c# asp.net-mvc api twitter twitter-rest-api

我正在尝试使用C#中的Twitter rest API发布直接消息,但无法获得结果。我通过更改基本字符串成功发布了状态更新,但在这种情况下没有。

        var oauth_token = "XXXX;  //user
        var oauth_token_secret = "XXXX";
        var oauth_consumer_key = "XXXX";  //this is my app
        var oauth_consumer_secret = "XXXX";

        //Request details

        var oauth_version = "1.0";
        var oauth_signature_method = "HMAC-SHA1";
        var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
        var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
       // var resource_url = "https://api.twitter.com/1.1/statuses/update.json";
        var resource_url = "https://api.twitter.com/1.1/direct_messages/new.json";
        var text = "message via rest api";
        var screen_name = "screenname";

        //encrypted oAuth signature

        var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
            "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}&status={7}";
        //&screen_name={7} &status={6}
        var baseString = string.Format(baseFormat,
                                    oauth_consumer_key,
                                    oauth_nonce,
                                    oauth_signature_method,
                                    oauth_timestamp,
                                    oauth_token,
                                    oauth_version,
                                    Uri.EscapeDataString(screen_name),
                                    Uri.EscapeDataString(text)
                                    );

        baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url),
                     "&", Uri.EscapeDataString(baseString));

        //Encrypt data

        var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                    "&", Uri.EscapeDataString(oauth_token_secret));

        string oauth_signature;
        using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
        {
            oauth_signature = Convert.ToBase64String(
                hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
        }

        //Finish Auth header

        var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
               "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
               "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
               "oauth_version=\"{6}\"";

        var authHeader = string.Format(headerFormat,
                                Uri.EscapeDataString(oauth_nonce),
                                Uri.EscapeDataString(oauth_signature_method),
                                Uri.EscapeDataString(oauth_timestamp),
                                Uri.EscapeDataString(oauth_consumer_key),
                                Uri.EscapeDataString(oauth_token),
                                Uri.EscapeDataString(oauth_signature),
                                Uri.EscapeDataString(oauth_version)
                        );

        //Disable exprect 100 continue header

        var postBody = "text=" + Uri.EscapeDataString(text);

        ServicePointManager.Expect100Continue = false;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
        request.Headers.Add("Authorization", authHeader);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        using (Stream stream = request.GetRequestStream())
        {
            byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
            stream.Write(content, 0, content.Length);
        }
        try
        {
            WebResponse response = request.GetResponse();
            ViewBag.Message = response.ToString();
        }
        catch (WebException e)
        {
            ViewBag.Message = e.Status;
        }

我不知道我错在哪里

3 个答案:

答案 0 :(得分:0)

您是否尝试过使用此工具来测试您的应用程序以及API? https://dev.twitter.com/rest/tools/console。我发现这非常有用,虽然进一步的实施很痛苦。

答案 1 :(得分:0)

错误位于编码部分,生成签名字符串,因为编码为double,如下所示是正确的:

答案 2 :(得分:0)

  var BaseString = String.Concat("include_entities=true",
                                                    "&oauth_consumer_key=" + Uri.EscapeDataString(oauth_consumer_key),
                                                    "&oauth_nonce=" + Uri.EscapeDataString(oauth_nonce),
                                                    "&oauth_signature_method=" + "HMAC-SHA1",
                                                    "&oauth_timestamp=" + Uri.EscapeDataString(oauth_timestamp),
                                                    "&oauth_token=" + Uri.EscapeDataString(oauth_token),
                                                    "&oauth_version=" + Uri.EscapeDataString(oauth_version),
                                                    "&status=" + Uri.EscapeDataString(Message));
            //Base String Signature
            var SignatureBaseString = String.Format("{0}&{1}&{2}",
                                                    method,
                                                    Uri.EscapeDataString(resource_url),
                                                    Uri.EscapeDataString(BaseString));