无法使用Twitter SDK 3.1.1在Tweet中上传视频

时间:2017-12-14 11:49:19

标签: android rest video upload twitterkit

我正在尝试使用我的Android应用中的REST API在Tweet中上传视频。 尝试使用INIT命令初始化上载文件会话时,我正在

  

代码:215,消息:认证数据不正确。

但是,身份验证工作正常,因为我能够使用StatusesService仅使用文本消息进行推文。 这是代码 -

public class MainActivity extends AppCompatActivity {
    public static final String consumerKey = "...";
    public static final String consumerSecret = "...";
    private static final String uploadEndpoint = "https://upload.twitter.com/1.1/media/upload.json";
    public TwitterLoginButton loginButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TwitterAuthConfig twitterAuthConfig = new TwitterAuthConfig(MainActivity.consumerKey, MainActivity.consumerSecret);
        TwitterConfig config = new TwitterConfig.Builder(this)
                .logger(new DefaultLogger(Log.DEBUG))
                .twitterAuthConfig(twitterAuthConfig)
                .debug(true)
                .build();
        Twitter.initialize(config);
        loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
        loginButton.setCallback(new Callback<TwitterSession>() {
            @Override
            public void success(Result<TwitterSession> result) {
                long sizeOfVideoInBytes = (new File(...)).length();
                HashMap<String, String> postParams = new HashMap<>();
                postParams.put("command", "INIT");
                postParams.put("media_type", "video/mp4");
                postParams.put("media_category", "tweet_video");
                postParams.put("total_bytes", String.valueOf(sizeOfVideoInBytes));

                TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
                TwitterAuthToken authToken = session.getAuthToken();
                String token = authToken.token;
                String secret = authToken.secret;
                HttpsURLConnection request = initTwitterApiRequest(uploadEndpoint, "POST", postParams, token, secret);
                enableStrictMode();
                try {
                    InputStream connectionInputStream;
                    int responseCode = request.getResponseCode();
                    if (responseCode < 400)
                        connectionInputStream = request.getInputStream();
                    else
                        connectionInputStream = request.getErrorStream();

                    StringBuffer response = new StringBuffer();

                    if(connectionInputStream != null) {
                        BufferedReader in = new BufferedReader(new InputStreamReader(connectionInputStream));
                        String inputLine;

                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();
                    }

                    Map<String, List<String>> map = request.getHeaderFields();

                    JSONObject headerJSON = new JSONObject();
                    if(map != null) {
                        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                            String key = entry.getKey();
                            String value = entry.getValue().get(0);

                            if(key == null) {
                                key = UUID.randomUUID().toString();
                            }
                            headerJSON.put(key, value);
                        }
                    }

                    String responseResult = "{'code':" + String.valueOf(request.getResponseCode());
                    if (!response.toString().equals("")) {
                        responseResult = responseResult + ",'data':" + response.toString();
                    }
                    if(headerJSON.length() > 0) {
                        responseResult = responseResult + ",'headers':" + headerJSON.toString();
                    }
                    responseResult = responseResult + "}";

                    request.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failure(TwitterException exception) {
                exception.printStackTrace();
            }
        });
    }
    public void enableStrictMode()
    {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        loginButton.onActivityResult(requestCode, resultCode, data);
    }

    private HttpsURLConnection initTwitterApiRequest(String url, String method, HashMap<String, String> postParams,
                                                     String token, String secret) {
        try {
            String paramString = "";
            for (Map.Entry<String, String> entry : postParams.entrySet()) {
                paramString = paramString + URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8") + "&";
            }
            String requestUrl = url;
            if(!paramString.isEmpty()) {
                paramString = paramString.substring(0, paramString.length() - 1);
                requestUrl = requestUrl + "?" + paramString;
            }
            URL httpsUrl = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) httpsUrl.openConnection();
            connection.setRequestMethod(method);
            TwitterAuthToken twitterAuthToken = new TwitterAuthToken(token, secret);
            TwitterAuthConfig twitterAuthConfig = new TwitterAuthConfig(consumerKey, consumerSecret);
            OAuthSigning oAuthSigning = new OAuthSigning(twitterAuthConfig, twitterAuthToken);
            Map<String, String> authHeaders = oAuthSigning.getOAuthEchoHeaders(method, url, postParams);
            for(Map.Entry<String, String> entry : authHeaders.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

我错过了什么吗?我该如何解决这个问题?

0 个答案:

没有答案