3

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

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

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

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

上传 HTTP 消息如下所示:

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 上。

是什么赋予了?

我在一篇随机博客文章中读到,使用 TwitPic+oAuth 要求我在单独的 HTTP 事务中发布推文消息,直接发送到 Twitter。嗯?我认为 oAuth 的邮件目的是允许消费者代表我做事——比如允许 TwitPic 为我发布推文。

有什么提示吗?


编辑
我在这里学到了更多。 这篇 2010 年 5 月的博文建议我使用 forX-Auth-Service-Provider的值https://api.twitter.com/1/account/verify_credentials.json告诉 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)."}]
}

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

4

2 回答 2

1

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

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

这就是我所拥有的。它是 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;
    }

}
于 2010-12-24T15:31:55.090 回答
1

我不知道最终答案,但我认为无论出于何种原因,在Raffi 的 2010 年 5 月的博客文章中被描述为“即将到来”的更改实际上并没有做出。

所以事实上,使用 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 库包,它应该非常简单。对于那些想要一个简单的人,你可以在这里得到一个:OAuth.cs。(获取 OAuthManager 下载)

于 2010-12-14T23:10:22.067 回答