1+ import java .io .IOException ;
2+ import java .net .URISyntaxException ;
3+ import java .util .ArrayList ;
4+
5+ import org .apache .http .HttpEntity ;
6+ import org .apache .http .HttpResponse ;
7+ import org .apache .http .NameValuePair ;
8+ import org .apache .http .client .HttpClient ;
9+ import org .apache .http .client .config .CookieSpecs ;
10+ import org .apache .http .client .config .RequestConfig ;
11+ import org .apache .http .client .methods .HttpGet ;
12+ import org .apache .http .client .utils .URIBuilder ;
13+ import org .apache .http .impl .client .HttpClients ;
14+ import org .apache .http .message .BasicNameValuePair ;
15+ import org .apache .http .util .EntityUtils ;
16+
17+ /*
18+ * Sample code to demonstrate the use of the Spaces lookup endpoint
19+ * */
20+ public class SpacesLookupDemo {
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+ //Replace SPACE_ID with the ID of a Space
29+ String response = getSpaceById ("SPACE_ID" , bearerToken );
30+ System .out .println (response );
31+ } else {
32+ System .out .println ("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable" );
33+ }
34+ }
35+
36+ /*
37+ * This method calls the Spaces lookup endpoint with the ID passed to it as a query parameter
38+ * */
39+ private static String getSpaceById (String spaceId , String bearerToken ) throws IOException , URISyntaxException {
40+ String searchResponse = null ;
41+
42+ HttpClient httpClient = HttpClients .custom ()
43+ .setDefaultRequestConfig (RequestConfig .custom ()
44+ .setCookieSpec (CookieSpecs .STANDARD ).build ())
45+ .build ();
46+
47+ URIBuilder uriBuilder = new URIBuilder ("https://api.twitter.com/2/spaces" );
48+ ArrayList <NameValuePair > queryParameters ;
49+ queryParameters = new ArrayList <>();
50+ queryParameters .add (new BasicNameValuePair ("ids" , spaceId ));
51+ uriBuilder .addParameters (queryParameters );
52+
53+ HttpGet httpGet = new HttpGet (uriBuilder .build ());
54+ httpGet .setHeader ("Authorization" , String .format ("Bearer %s" , bearerToken ));
55+ httpGet .setHeader ("User-Agent" , "v2SpacesLookupJava" );
56+ httpGet .setHeader ("Content-Type" , "application/json" );
57+
58+ HttpResponse response = httpClient .execute (httpGet );
59+ HttpEntity entity = response .getEntity ();
60+ if (null != entity ) {
61+ searchResponse = EntityUtils .toString (entity , "UTF-8" );
62+ }
63+ return searchResponse ;
64+ }
65+
66+ }
0 commit comments