3

C#で記述された.NETアプリから、OAuthを使用してTwitPicに写真をアップロードしています。

oAuthのものは少し注意が必要です。それを処理するための2ビットの.NETコードを見つけましたが、どちらにも満足できませんでした。 DotNetOpenAuthは、私が必要とする以上にかなり重いようでした。(oAuth署名とトークンリクエストを実行したいだけです)。OAuthBase.csコードは、私には混乱していてエレガントではないように見えました。私は6つの文字列パラメーターをメソッドに渡さなければなりませんでした。

だから私はそれを自分で行うためにいくつかのコードを書きました、それはかなり小さく、それはうまくいくようです。「リクエストトークン」を取得するために動作します。これは、認証Webページをポップし、「アクセストークン」を取得するために機能します。また、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月のこのブログ投稿は、の値を使用すると、 TwitPicがリクエストを受け取ったときにtwitter.comで「verify_credentials.json」を呼び出すようX-Auth-Service-Providerに指示することを示唆しています。https://api.twitter.com/1/account/verify_credentials.json本当に私の資格情報を確認しているだけの場合、これはツイートが投稿されない理由を説明します。

投稿はまた、それを交換して置き換えることで、TwitPicを介して委任を使用してTwitterを更新できるようになるhttps://api.twitter.com/1/status/update.json はずだと示唆しています。しかし、これは前向きな投稿です。この機能を利用するには、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コメントを取得できることがわかりました。これにより、Eplixo(http://eplixo.com/m/)ビデオチャットおよびTwitterクライアントのTwitterユーザーアカウントに画像が投稿されます。

しかし、私は応答を得ることができないようです。これで、投稿とアップロードを行うことができますが、アプリケーションの他の部分の応答データを取得する方法を理解しておくと便利です。

これが私が持っているものです。これは、TwipliAPIラッパーのバリエーションです。

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

最終的な答えはわかりませんが、2010年5月のRaffiのブログ投稿で「RealSoon Now」と記載されていた変更は、何らかの理由で実際には行われていないと思います。

したがって、実際には、OAuthを使用して、TwitPicとTwitterに別々に投稿する必要があります。

ただし、Twitterでこれを行うのは難しくありません。statuses /update.xmlURLで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);
    }
}

そのコードには2つのトリッキーな部分があります。1つはUrlEncode()呼び出しです。OAuthは、urlencodingが大文字を使用する必要があることを指定します。組み込みの.NETルーチンは小文字を使用します。だから、必ず大文字にしてください。

2番目のトリッキーな部分は、OAuth認証ヘッダーを取得することです。OAuthライブラリパッケージを使用する場合、それは非常に単純なはずです。簡単なものが必要な場合は、OAuth.csから入手できます。(OAuthManagerのダウンロードを取得します)

于 2010-12-14T23:10:22.067 に答える