|
| 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 Quote Tweets endpoint |
| 19 | + * */ |
| 20 | +public class QuoteTweetsDemo { |
| 21 | + |
| 22 | + // To set your environment 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 | + final String bearerToken = System.getenv("BEARER_TOKEN"); |
| 27 | + if (null != bearerToken) { |
| 28 | + //Replace with Tweet ID below |
| 29 | + String response = getTweets(20, 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 v2 Quote Tweets endpoint by Tweet ID |
| 38 | + * */ |
| 39 | + private static String getTweets(int tweetId, String bearerToken) throws IOException, URISyntaxException { |
| 40 | + String tweetResponse = null; |
| 41 | + |
| 42 | + HttpClient httpClient = HttpClients.custom() |
| 43 | + .setDefaultRequestConfig(RequestConfig.custom() |
| 44 | + .setCookieSpec(CookieSpecs.STANDARD).build()) |
| 45 | + .build(); |
| 46 | + |
| 47 | + URIBuilder uriBuilder = new URIBuilder(String.format("https://api.twitter.com/2/tweets/%s/quote_tweets", tweetId)); |
| 48 | + ArrayList<NameValuePair> queryParameters; |
| 49 | + queryParameters = new ArrayList<>(); |
| 50 | + queryParameters.add(new BasicNameValuePair("tweet.fields", "created_at")); |
| 51 | + uriBuilder.addParameters(queryParameters); |
| 52 | + |
| 53 | + HttpGet httpGet = new HttpGet(uriBuilder.build()); |
| 54 | + httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken)); |
| 55 | + httpGet.setHeader("Content-Type", "application/json"); |
| 56 | + |
| 57 | + HttpResponse response = httpClient.execute(httpGet); |
| 58 | + HttpEntity entity = response.getEntity(); |
| 59 | + if (null != entity) { |
| 60 | + tweetResponse = EntityUtils.toString(entity, "UTF-8"); |
| 61 | + } |
| 62 | + return tweetResponse; |
| 63 | + } |
| 64 | +} |
0 commit comments