简体   繁体   English

Twitter API使用仅应用程序身份验证获取Tweet返回HTTP状态代码401

[英]Twitter API to get Tweets using Application Only Authentication returns HTTP Status Code 401

I am experimenting with Twitter APIs using Java. 我正在试验使用Java的Twitter API。 I am trying to access the APIs using application only authentication using twitter documentation Twitter Application-only authentication 我正在尝试使用Twitter文档的仅应用程序身份验证来访问API Twitter仅应用程序身份验证

Here is my code. 这是我的代码。 I have also tried NOT to Base64 encode the access_token as suggested in this question 我也曾尝试不对Base64编码access_token进行编码,如该问题所示

public class TwitterAppOnlyAuthenticationClass {
    private static final String consumerKey = "My Consumer Key";
    private static final String consumerSecret  = "My Consumer Secret";

    private static OAuthAccessToken getAccessToken() throws UnsupportedEncodingException, IOException {

        // Encode Consumer Key and Secret

        String encodedConsumerKeyandToken = null;

        encodedConsumerKeyandToken = Base64.getEncoder().encodeToString(
                (URLEncoder.encode(consumerKey, "UTF-8") + ":" +
                        URLEncoder.encode(consumerSecret, "UTF-8")).getBytes());


        //Get the bearer token

        String urlString = "https://api.twitter.com/oauth2/token";
        String httpMethod = "POST";

        OAuthAccessToken oaat = null;

        URL url;

        url = new URL (urlString);
        HttpsURLConnection u = (HttpsURLConnection)url.openConnection();



        u.setDoOutput(true);

        u.setRequestMethod(httpMethod);
        u.setRequestProperty("Authorization", "Basic " + encodedConsumerKeyandToken);
        u.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        OutputStream dos = u.getOutputStream();
        dos.write("grant_type=client_credentials".getBytes());
        dos.flush();
        dos.close();

        u.connect();

        JsonObject jO = (JsonObject)((Json.createReader(u.getInputStream())).read());

        System.out.println(jO.toString());

        oaat = new OAuthAccessToken();
        oaat.setTokenType(jO.getString("token_type"));
        oaat.setAccessToken(jO.getString("access_token"));

        return oaat;


    }


    public static void main(String[] args) {

        //Basic Java program to retrieve a collection of the most recent Tweets posted by the user


        try {

            OAuthAccessToken oaat = getAccessToken();
            System.out.println("Access Token : " + oaat.getAccessToken());

            //Make the call to {GET statuses/user_timeline}

            String urlString = "https://api.twitter.com/1.1/statuses/user_timeline.json?count=100&screen_name=twitterapi";
            String httpMethod = "GET";

            URL url;

            url = new URL (urlString);
            HttpsURLConnection u = (HttpsURLConnection)url.openConnection();

            u.setDoOutput(true);
            u.setRequestMethod(httpMethod);
            u.setRequestProperty("Authorization", "Bearer " + oaat);

            u.connect();

            JsonObject jO = (JsonObject)((Json.createReader(u.getInputStream())).read());
            System.out.println(jO.toString());


        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.exit(-1);
        }

    }

}

Your code is a bit clumsy, however if you look at this line; 您的代码有点笨拙,但是,如果您看一下这一行;

u.setRequestProperty("Authorization", "Bearer " + oaat);

You are calling the toString() method of your oaat object (which I doubt you have implemented). 您正在调用oaat对象的toString()方法(我怀疑您已经实现了该方法)。 Only the access_token value itself is needed. 仅需要access_token值本身。 This is why you're getting code 401 corresponding to an invalid token as specified in the docs. 这就是为什么您要获得与文档中指定的无效令牌相对应的代码401原因。 Hence, change it to oaat.getAccessToken() and it will work. 因此,将其更改为oaat.getAccessToken()使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM