2

Twitterに画像を投稿する必要があります。アプリに Twitter を統合しました。URL リンクではなく、画像そのものをツイートする必要があります。TwitPic を使用したくありません。

次のコードを使用して、マルチパート エンティティを作成しました。404エラーが発生します。

Bitmap bm = null;
                String encodedImage = "";
                try {

                    URL aURL = new URL("http://50.57.227.117/blacksheep/uploaded/Detailed_images/961314275649aladdins.jpg");
                    URLConnection conn = aURL.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is, 8192);
                    bm = BitmapFactory.decodeStream(bis);
                    bis.close();
                    is.close();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
                     imageBytes = baos.toByteArray();
                     encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
                     Log.v("encodedImage >>",encodedImage); 

                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(
                        "https://api.twitter.com/1.1/statuses/update_with_media.json");
               ByteArrayBody bab = new ByteArrayBody(imageBytes, "forest.jpg");

                MultipartEntity reqEntity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
              reqEntity.addPart("media", bab);
                reqEntity.addPart("status", new StringBody("test image"));
                postRequest.setEntity(reqEntity);
                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();

                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                System.out.println("Response: " + s);
            // Update status
            //twitter4j.Status response = twitter.updateStatus(encodedImage);
        //  twitter4j.Status response1 = twitter.updateStatus(status);

            //Log.d("Status", "> " + response1.getText());
        } catch (TwitterException e) {
            // Error in updating status
            Log.d("Twitter Update Error", e.getMessage());
        }
4

2 に答える 2

5

最初の試み:

そのため、Apache の古い http クライアントを使用して、twitter との統合を支援するために使用していたライブラリの外部にリクエストを作成しているように見えました。私あなたが最新の 3.03 より前のバージョンを使用していて、アップグレードしたくないと思っていたと思います。ほら、update_with_media はかなり新しいので、あなたのバージョンがそれを実装しているとは思いませんでした。

あなたがしていたことの問題は、twitter が認証にoauthを使用していることです。そのため、取得したアクセス トークンを使用してリクエストに「署名」する必要があります。知る限り、Twitter4j がこれを行います。認証を壊すことなく、素敵なヘルパーライブラリを参照せずに、別のクライアントを使用していくつかの呼び出しを行うことはできません

エンドポイント../update_with_mediaは、現在認証中のユーザーのステータスを更新するように定義されています。リクエストにアクセストークンもユーザーも含まれていないため、そのエンドポイントは意味をなさないので、Twitterはそれを(無許可)404ではなく(見つからない)と解釈していたのではないかと思います401

したがって、最初の試みは、twitter4j へのアップグレードを要求しないことでした。時々アップグレードするのは面倒です!代わりに、このブログで詳しく説明されているように、ライブラリをハックできます。しかし、ライブラリが異なるため、それは簡単ではありませんでした。

それで、あなたが本当にtwitter4jに別のリクエストをしたいのであれば、私たちが試すことができる他の何かは、おそらくそれを簡単にするためにスクライブを使用して、実際に署名を行うことでした....大まかに:

        final OAuthService myTwitterService = TwitterClient.getTwitterClient().getService();
        final OAuthRequest aNiceOAuthRequest = new org.scribe.model.OAuthRequest(
                YOURPOST, THATURL);

2 回目の試行:

しかし、これをすべて行うわけではありません。いずれにせよ、最新バージョンの twitter4j を使用していることがわかります最初に袋小路に行って申し訳ありません-私は想定すべきではありませんでしたが、他の誰かが必要とする場合に役立つように上記を含めました.

最新バージョンでは、このエンドポイントのドキュメントが実装されていることがわかりましたStatusUpdate代わりにオブジェクトを取ることを除いて。だからあなたは次のようなことをしたい:

final StatusUpdate statusUpdate = new StatusUpdate("Hallee hallo my status java.lang.String here...");
       // now do as you did until:
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
                 imageBytes = baos.toByteArray();
                 encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
       // then flip the stream
       byte[] myTwitterUploadBytes = bos.toByteArray();
       ByteArrayInputStream bis = new ByteArrayInputStream(myTwitterUploadBytes);
       // doo and double check your encoding etc, similar to in your question..
       statusUpdate.setMedia("give me a java.lang.String name", bis);
       // then continue just using twitter for j- update status as you would
       //... get twitter etc...
       //
       twitter4j.Status response = twitter.updateStatus(statusUpdate);

現在、テストするボックスを持っていません-ほぼ正しいはずです. それでも 404 が表示される場合、応答のエラー コードは何ですか? 認証されていますか?

それでもうまくいかない場合は、バックアップとして上記のいくつかを試すこともできます。

お役に立てれば、

一番、

トム。

于 2013-05-24T14:56:48.493 に答える
2

4.0.3 (おそらくそれ以前) を使用すると、twitter4j を使用してツイートに画像を埋め込むのは非常に簡単です。

Twitter                         twtobj;
StatusUpdate                    stsupd;
Status                          stsres;

twtobj=twitterFactory.getInstance();
twtobj.setOAuthConsumer(csmkey,csmsec);
twtobj.setOAuthAccessToken(new AccessToken(acstkn,acssec));

stsupd=new StatusUpdate(msgtxt);
if(medurls.length>0) {
    long[]                      medidns=new long[medurls.length];

    for(int xa=0; xa<medurls.length; xa++) {
        String                  medurl=Util.resolveRelativeUrl(medurls[xa]);
        InputStream             imgstm=null;

        try {
            imgstm=new URL(medurl).openConnection().getInputStream();
            medidns[xa]=twtobj.uploadMedia(medurl,imgstm).getMediaId();                     // this actually uploads the image to Twitter at this point
            }
        catch(MalformedURLException thr) { throw new ShfFail(Fail.IMAGE_URL ,"The media URL is not valid: " +medurl+" ("+thr.getMessage()+")"); }
        catch(IOException           thr) { throw new ShfFail(Fail.IMAGE_READ,"The media could not be read: "+medurl+" ("+thr.getMessage()+")"); }
        finally                          { GenUtil.close(imgstm); }
        }
    stsupd.setMediaIds(medidns);
    }
stsres=twtobj.updateStatus(stsupd);

2015-06-10 の時点で、最大 4 つの画像、または 1 つのアニメーション GIF、または 1 つのビデオが許可されていることに注意してください。

また、画像ストリームをキャプチャして、外側のブロックで明示的に閉じていることにも注意してください (表示されていません)。これは不必要かもしれませんが、その肯定的な確認を見つけることができません。

誰かが気になる場合resolveRelativeUrlsは、相対パスを現在のフォルダーからのファイル URL として解決できるようにすると便利です。

static public String resolveRelativeUrl(String url) {
    if(!TextUtil.stringCT(url,"://")) {
        url=new File(url).getAbsoluteFile().toURI().toString();
        }
    return url;
    }

ユーティリティ メソッドstringCTは大文字と小文字を区別しません。

于 2015-06-11T03:13:50.370 に答える