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

I am experimenting with Twitter APIs using Java. I am trying to access the APIs using application only authentication using twitter documentation Twitter Application-only authentication

Here is my code. I have also tried NOT to Base64 encode the access_token as suggested in this question

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);
        }

    }

}

Solution 1:

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). Only the access_token value itself is needed. This is why you're getting code 401 corresponding to an invalid token as specified in the docs. Hence, change it to oaat.getAccessToken() and it will work.