Tuesday 22 April 2014

Sample Java code for obtaining an authorisation token for your Twitter application

Here is an example of how to obtain an authorisation token from Twitter, using your registered application's API key and API secret.

The relevant REST API documentation can be found at: https://dev.twitter.com/docs/api/1.1/post/oauth2/token

For the HTTP client I have made use of the ever popular Apache HTTP client (v4).

The response should include a JSON document containing a property keyed by access_token.

There are a few potential gotchas involved with including this in a multithreaded application, so I'd recommend that you read Twitter's documentation carefully.

        final String basicAuthentication = TwitterCredentials.API_KEY + 
                ":" + TwitterCredentials.API_SECRET;
        String base64EncodedAuthentication = Base64.getEncoder().encodeToString(basicAuthentication.getBytes(StandardCharsets.UTF_8));

        HttpClient client = new DefaultHttpClient();

        HttpHost httpHost = new HttpHost("api.twitter.com", 443, "https");

        HttpPost httpRequest = new HttpPost("https://api.twitter.com/oauth2/token?grant_type=client_credentials");

        Header authenticationHeader = new BasicHeader("Authorization", "Basic " + base64EncodedAuthentication);
        httpRequest.addHeader("Content-Type", "application/json; charset=utf-8");

        HttpResponse httpResponse = client.execute(httpHost, httpRequest);

        HttpEntity entity = httpResponse.getEntity();

        String responseBody = EntityUtils.toString(entity);

No comments:

Post a Comment