【问题标题】:using TwitPic + OAuth to upload a photo + tweet to Twitter (.NET C#) - why no tweet?使用 TwitPic + OAuth 将照片 + 推文上传到 Twitter (.NET C#) - 为什么没有推文?
【发布时间】:2011-05-24 23:45:45
【问题描述】:

我正在使用 OAuth 从一个用 C# 编写的 .NET 应用程序将照片上传到 TwitPic。

oAuth 的东西有点棘手。我找到了两段 .NET 代码来处理它,但都不满意。 DotNetOpenAuth 似乎很重,超过了我的需要。 (只想做 oAuth 签名和令牌请求)。 OAuthBase.cs 代码对我来说似乎很混乱和不雅。我必须将 6 个字符串参数传递给方法,如果出现任何问题,那我就倒霉了。

所以我自己编写了一些代码,它相当小,而且似乎可以工作。它用于获取“请求令牌”。它可以弹出授权网页并获取“访问令牌”。它还可以将照片上传到 TwitPic。

所有 HTTP 响应都返回 200 或 201。

upload HTTP message 看起来像这样:

POST http://api.twitpic.com/2/upload.json HTTP/1.1
Content-Type: multipart/form-data; boundary=48cb9a6d-1f1d-432d-b6e3-307e32e8228a
X-Auth-Service-Provider: https://api.twitter.com/1/account/verify_credentials.json
X-Verify-Credentials-Authorization: OAuth realm="http://api.twitter.com/",
  oauth_consumer_key="Dv1er93yKzEMn74hZfPmJA",
  oauth_nonce="51fi305k",
  oauth_signature="4oWcmZcd%2F%2F81JslJ70xFXFm8%2BQs%3D",
  oauth_signature_method="HMAC-SHA1",
  oauth_timestamp="1292277715",
  oauth_token="59152613-z8EP4GoYS1Mgo3E29JfIqBnyTRlruAJs8Bkvs3q0T",
  oauth_version="1.0"
Host: api.twitpic.com
Content-Length: 14605
Expect: 100-continue
Connection: Keep-Alive

--48cb9a6d-1f1d-432d-b6e3-307e32e8228a
Content-Disposition: file; name="media"; filename="CropperCapture[10].jpg"
Content-Type: image/jpeg
....
--48cb9a6d-1f1d-432d-b6e3-307e32e8228a
Content-Disposition: form-data; name="key"

twitpic-api-key-here
--48cb9a6d-1f1d-432d-b6e3-307e32e8228a
Content-Disposition: form-data; name="message"

uploaded from Yappy. (at 12/13/2010 5:01:55 PM)
--48cb9a6d-1f1d-432d-b6e3-307e32e8228a--

我上传回来的json是这样的:

{"id":"3f0jeiw5",
 "text":"uploaded from Yappy. (at 12\/13\/2010 5:01:55 PM)",
 "url":"http:\\/twitpic.com\/3f0jeiw5",
 "width":257,
 "height":184,
 "size":14156,
 "type":"jpg",
 "timestamp":"Mon, 13 Dec 2010 22:02:06 +0000",
 "user":{
   "id":54591561,"screen_name":"bfavre"}
}

但问题是,在我将图片上传到 Twitpic 后,该图片在 TwitPic 上可用,但相关消息从未出现在 Twitter 上。

什么给了?

我在a random blog post 中读到,使用 TwitPic+oAuth 要求我在单独的 HTTP 事务中将推文消息直接发布到 Twitter。嗯?我认为 oAuth 的邮件目的是允许消费者代表我做事——比如允许 TwitPic 为我发布推文。

有什么提示吗?


编辑
我在这里学习更多。 2010 年 5 月的 This blog post 向我建议,使用 https://api.twitter.com/1/account/verify_credentials.jsonX-Auth-Service-Provider 的值告诉 TwitPic 在收到我的请求时在 twitter.com 上调用“verify_credentials.json”。如果它真的只是在验证我的凭据,这将解释为什么没有发布推文。

帖子还建议将其替换为https://api.twitter.com/1/status/update.json应该允许我通过 TwitPic 授权更新 Twitter。但这是一篇具有前瞻性的文章——它说获得这种能力需要 Twitter 的工作。

我还没有找到执行此操作的示例 HTTP 消息。任何人?


更新
将验证 URL 转换为 https://api.twitter.com/1/status/update.json 并使用 POST 进行签名后,我得到一个 401 响应代码:

{"errors":
  [{"code":401,
    "message":"Could not authenticate you (header rejected by twitter)."}]
}

这与here, in the twitter dev forum 描述的问题基本相同。该线程末尾的建议是签名计算算法是错误的,但我认为这是不正确的,因为我的 sig 算法适用于所有其他请求。

【问题讨论】:

    标签: .net twitter oauth twitpic


    【解决方案1】:

    我一直在使用 Twitpic API 来生成 oAuth 集成,发现我可以从 Twitpic 获取发布的图像和随图像一起发送的 Twitter 评论。这会将图像发布到我们的 Epixo (http://eplixo.com/m/) 视频聊天和推特客户端的推特用户帐户

    但是我似乎无法得到回应。现在我可以忍受它发布和上传,但弄清楚如何获取应用程序其他部分的响应数据会很有用。

    这就是我所拥有的。它是 Twipli API 包装器的变体

    protected void Button1_Click(object sender, EventArgs e)
    {
    
        string ct = img.PostedFile.ContentType.ToString();
        string usertoken = Session["usrToken"].ToString();
        string userSecret = Session["usrSecret"].ToString();
        string conkey = Session["ConsumerKey"].ToString();
        string consecret = Session["ConsumerSecret"].ToString();
        string twitkey = Session["twitpickey"].ToString();
    
        string _m = m.Text; // This takes the Tweet to be posted
    
    
        HttpPostedFile myFile = img.PostedFile;
        string fileName = myFile.FileName.ToString();
    
        int nFileLen = myFile.ContentLength;
        byte[] myData = new byte[nFileLen];
        myFile.InputStream.Read(myData, 0, nFileLen);
    
        TwitPic tw = new TwitPic();
        upres.Text = tw.UploadPhoto(myData, ct, _m, fileName, twitkey, usertoken, userSecret, conkey, consecret).ToString();
        Response.Redirect("twittercb.aspx?oauth_verifier=none");
    }
    public class TwitPic
    {
        private const string TWITPIC_UPLADO_API_URL = "http://api.twitpic.com/2/upload";
        private const string TWITPIC_UPLOAD_AND_POST_API_URL = "http://api.twitpic.com/1/uploadAndPost";
        /// 
        /// Uploads the photo and sends a new Tweet
        /// 
        /// <param name="binaryImageData">The binary image data.
        /// <param name="tweetMessage">The tweet message.
        /// <param name="filename">The filename.
        /// Return true, if the operation was succeded.
        public string UploadPhoto(byte[] binaryImageData, string ContentType, string tweetMessage, string filename, string tpkey, string usrtoken, string usrsecret, string contoken, string consecret)
        {            
            string boundary = Guid.NewGuid().ToString();
            string requestUrl = String.IsNullOrEmpty(tweetMessage) ? TWITPIC_UPLADO_API_URL : TWITPIC_UPLOAD_AND_POST_API_URL;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            string encoding = "iso-8859-1";
    
            request.PreAuthenticate = true;
            request.AllowWriteStreamBuffering = true;
            request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            request.Method = "POST";
    
            string header = string.Format("--{0}", boundary);
            string footer = string.Format("--{0}--", boundary);
    
            StringBuilder contents = new StringBuilder();
            contents.AppendLine(header);
    
            string fileContentType = ContentType;
            string fileHeader = String.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", "media", filename);
            string fileData = Encoding.GetEncoding(encoding).GetString(binaryImageData);
    
            contents.AppendLine(fileHeader);
            contents.AppendLine(String.Format("Content-Type: {0}", fileContentType));
            contents.AppendLine();
            contents.AppendLine(fileData);
    
            contents.AppendLine(header);
            contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "key"));
            contents.AppendLine();
            contents.AppendLine(tpkey);
    
            contents.AppendLine(header);
            contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "consumer_token"));
            contents.AppendLine();
            contents.AppendLine(contoken);
    
            contents.AppendLine(header);
            contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "consumer_secret"));
            contents.AppendLine();
            contents.AppendLine(consecret);
    
            contents.AppendLine(header);
            contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "oauth_token"));
            contents.AppendLine();
            contents.AppendLine(usrtoken);
    
            contents.AppendLine(header);
            contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "oauth_secret"));
            contents.AppendLine();
            contents.AppendLine(usrsecret);
    
            if (!String.IsNullOrEmpty(tweetMessage))
            {
                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "message"));
                contents.AppendLine();
                contents.AppendLine(tweetMessage);
            }
    
            contents.AppendLine(footer);            
            byte[] bytes = Encoding.GetEncoding(encoding).GetBytes(contents.ToString());            
            request.ContentLength = bytes.Length;
    
            string mediaurl = "";
            try
            {
                using (Stream requestStream = request.GetRequestStream()) // this is where the bug is due to not being able to seek.
                {        
                    requestStream.Write(bytes, 0, bytes.Length); // No problem the image is posted and tweet is posted
                    requestStream.Close();                       
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) // here I can't get the response
                    { 
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            string result = reader.ReadToEnd();
    
                            XDocument doc = XDocument.Parse(result); // this shows no root elements and fails here
    
                            XElement rsp = doc.Element("rsp");
                            string status = rsp.Attribute(XName.Get("status")) != null ? rsp.Attribute(XName.Get("status")).Value : rsp.Attribute(XName.Get("stat")).Value;
                            mediaurl = rsp.Element("mediaurl").Value;
                            return mediaurl;                            
                        } 
                    } 
    
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            } 
            return mediaurl;
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      我不知道最终答案,但我认为无论出于何种原因,Raffi's blog post of May 2010 中被描述为“即将实现”的更改实际上并未进行。

      所以事实上,使用 OAuth,您确实必须分别在 TwitPic 和 Twitter 上发帖。

      不过,在 Twitter 中做到这一点并不难。只需在 statuses/update.xml URL 上进行 POST。

      private void Tweet(string message)
      {
          var twitterUpdateUrlBase = "http://api.twitter.com/1/statuses/update.xml?status=";
          var url = twitterUpdateUrlBase + UrlEncode(message);
      
          var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
      
          var request = (HttpWebRequest)WebRequest.Create(url);
          request.Method = "POST";
          request.PreAuthenticate = true;
          request.AllowWriteStreamBuffering = true;
          request.Headers.Add("Authorization", authzHeader);
      
          using (var response = (HttpWebResponse)request.GetResponse())
          {
              if (response.StatusCode != HttpStatusCode.OK)
              MessageBox.Show("There's been a problem trying to tweet:" +
                              Environment.NewLine +
                              response.StatusDescription +
                              Environment.NewLine +
                              Environment.NewLine +
                              "You will have to tweet manually." +
                              Environment.NewLine);
          }
      }
      

      该代码有两个棘手的部分:首先是 UrlEncode() 调用。 OAuth 指定 urlencoding 必须使用大写字母。内置的 .NET 例程使用小写字母。所以一定要大写。

      第二个棘手的部分是获取 OAuth 授权标头。如果您使用 OAuth 库包,它应该非常简单。想要简单的可以get one here: OAuth.cs。 (获取 OAuthManager 下载)

      【讨论】:

      • 仅供参考 - 我喜欢你简单的 OAuth 库。我做了一个快速修复来处理扩展字符,并在这里发布:cropperplugins.codeplex.com/discussions/249415
      • 只是跟进 - 谢谢,您的更改现在在 OAuth 库中;另外,现在有一个DLL,任何人都可以下载。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多