1+ import org .apache .http .HttpEntity ;
2+ import org .apache .http .HttpResponse ;
3+ import org .apache .http .NameValuePair ;
4+ import org .apache .http .client .HttpClient ;
5+ import org .apache .http .client .config .CookieSpecs ;
6+ import org .apache .http .client .config .RequestConfig ;
7+ import org .apache .http .client .methods .HttpGet ;
8+ import org .apache .http .client .utils .URIBuilder ;
9+ import org .apache .http .impl .client .HttpClients ;
10+ import org .apache .http .message .BasicNameValuePair ;
11+ import org .apache .http .util .EntityUtils ;
12+
13+ import java .io .IOException ;
14+ import java .net .URISyntaxException ;
15+ import java .util .ArrayList ;
16+
17+ /*
18+ * Sample code to demonstrate the use of the v2 Usage Tweets endpoint
19+ * */
20+ public class UsageTweetsDemo {
21+
22+ // To set your enviornment variables in your terminal run the following line:
23+ // export 'BEARER_TOKEN'='<your_bearer_token>'
24+
25+ public static void main (String args []) throws IOException , URISyntaxException {
26+ String bearerToken = System .getenv ("BEARER_TOKEN" );
27+ if (null != bearerToken ) {
28+ String response = getUsageTweets (bearerToken );
29+ System .out .println (response );
30+ } else {
31+ System .out .println ("There was a problem getting you bearer token. Please make sure you set the BEARER_TOKEN environment variable" );
32+ }
33+ }
34+
35+ /*
36+ * This method calls the v2 Usage Tweets endpoint
37+ * */
38+ private static String getUsageTweets (String bearerToken ) throws IOException , URISyntaxException {
39+ String usageTweetsResponse = null ;
40+
41+ HttpClient httpClient = HttpClients .custom ()
42+ .setDefaultRequestConfig (RequestConfig .custom ()
43+ .setCookieSpec (CookieSpecs .STANDARD ).build ())
44+ .build ();
45+
46+ URIBuilder uriBuilder = new URIBuilder ("https://api.twitter.com/2/usage/tweets" );
47+ HttpGet httpGet = new HttpGet (uriBuilder .build ());
48+ httpGet .setHeader ("Authorization" , String .format ("Bearer %s" , bearerToken ));
49+ httpGet .setHeader ("Content-Type" , "application/json" );
50+
51+ HttpResponse response = httpClient .execute (httpGet );
52+ HttpEntity entity = response .getEntity ();
53+ if (null != entity ) {
54+ usageTweetsResponse = EntityUtils .toString (entity , "UTF-8" );
55+ }
56+ return usageTweetsResponse ;
57+ }
58+ }
0 commit comments