0

そのため、Twitterは認証の方法をOAuthに変更し、ついにアプリを更新するしかありませんでした。Twitterのものを機能させました(アプリケーションに保存されたOAuth情報が少しあります)。次に、TwitPicAPIを再び機能させる必要があります。私が見つけたOAuthを処理するライブラリはないので、ここで見つけたものに基づいて手動で行う必要があります。

http://dev.twitpic.com/docs/2/upload/

私はゆっくりですが確実にそこに着いていると思います。私は決してこの種のものの専門家ではありませんが、他のAPI呼び出しを受け取りました:http: //dev.twitpic.com/docs/2/users_show それは魅力のように機能していますが、それはマルチパートではありませんそこに画像のあるデータ。

私はさらに調査を行い、OAuthを実行するために使用している素晴らしいTwitterizerフレームワークが多くの作業を行っていることを認識しました。つまり、各リクエストに署名し、OAuthトークンの数ビットを渡すだけで済みます。そのため、TwitPicにアップロードするための上記のメソッド呼び出しでは、同じ方法で署名する必要があることに気付きました。これは難しい部分です。署名を取得し、webrequestを使用して渡すことです。

これも私を混乱させるものです、彼らはOAuthエコー部分がヘッダーで渡される署名を言っています、これはC#を使用してヘッダーを作成するのと同じSystem.Net.WebHeaderCollection webhc = new System.Net.WebHeaderCollection();ですか?

私は何をしなければならないかを知っています、どういうわけか私のOAuthトークン(JSONにシリアル化された)で呼び出されたリクエストを取得し、署名を構築し、実際のAPIを呼び出して、3つのパラメーター(JSONシリアル化)を渡します:キー、メッセージ、ファイル。

このファイルはメモリ常駐ファイルであるため、私もつまずきます。このデータを渡す方法がわかりません。古いTwitPicライブラリのコードスニペットがあります。

    string fileContentType = "image/jpeg";//GetImageContentType(filename);
    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);

問題は、JSONを使用してこれらすべてを実行しようとしていることです。fileContentTypeなどを構築してすべてをStringBuilderコンテンツオブジェクトに追加することは、私が必要とするよりもはるかに手作業のように思えます。

ファイル、メッセージ、OAuthトークンを渡すTwitterの新しい認証用のTwitPicAPIがあればいいのにと思います。悲しいかな...正しい方向へのステアリングは大歓迎です。

完全を期すために投稿されたのは、私が持っている古いアップロードファイルの方法です。

    // <summary>
    // Uploads the photo and sends a new Tweet
    // </summary>
    // <param name="binaryImageData">The binary image data.</param>
    // <param name="tweetMessage">The tweet message.</param>
    // <param name="filename">The filename.</param>
    // <returns>Return true, if the operation was succeded.</returns>
    public bool UploadPhoto(byte[] binaryImageData, string tweetMessage, string  filename)
    {
        // Documentation: http://www.twitpic.com/api.do
        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 = "image/jpeg";//GetImageContentType(filename);
        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}\"", "username"));
        contents.AppendLine();
        //contents.AppendLine(this.Username);

        contents.AppendLine(header);
        contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "password"));
        contents.AppendLine();
        //contents.AppendLine(this.Password.ToInsecureString());

        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;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(bytes, 0, bytes.Length);

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string result = reader.ReadToEnd();

                    XDocument doc = XDocument.Parse(result);

                    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;

                    return status.ToUpperInvariant().Equals("OK");
                }
            }
        }
    }
4

2 に答える 2

1

修正は実際には非常に簡単です。問題は投稿先の URL です。あなたの行で:

private const string TWITPIC_UPLOAD_AND_POST_API_URL = "http://api.twitpic.com/1/uploadAndPost";

に変更する必要があります

private const string TWITPIC_UPLOAD_AND_POST_API_URL = "http://api.twitpic.com/1/uploadAndPost.xml";

また

private const string TWITPIC_UPLOAD_AND_POST_API_URL = "http://api.twitpic.com/1/uploadAndPost.json";

これにより、応答タイプが得られます。XDocument を使用して結果を解析する方法に関連するコードの部分を変更する必要があります。上記で使用する URL に応じて、応答は XML または JSON のいずれかになります。あなたの例は XML に適していますが、結果のコードは探しているものに近くありません。結果コードの例を見たい場合は、http://dev.twitpic.com/docs/1/uploadAndPost/で表示できます。

たとえば、次の行を削除します。

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;

次に、

mediaurl = doc.Element("image").Element("url").Value;

または、JSON のデバッガーを実行することもできます。誰かがそれを必要として要求すれば、完全なコードを作成できます。

于 2011-03-26T22:21:50.553 に答える
0

これを可能にする Twipli API ラッパーのバリエーションを次に示します。私が持っている唯一の問題は、返されたデータのサードパーティ操作の結果で応答できないことです。ただし、Twitter に投稿し、画像を正しくアップロードします。非常に多くの頭が 1 つよりも優れているので、解決策を思いついたら教えてください。

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:41:36.290 に答える