当前位置:   article > 正文

推特API(Twitter API)V2 用户关注、推文相关_twitter api v2

twitter api v2

        前面章节已经介绍使用code换取Token的整个流程了,这里不再重复阐述了,下面我们获取到用户token以后如何帮用户自动关注别人。需要参数关注者的用户ID(token授权用户)以及关注的目标用户ID。用户ID如何获取可以看上一章节获取用户信息里面就有用户ID参数。

1.引入相关依赖Maven

  1. <dependency>
  2. <groupId>oauth.signpost</groupId>
  3. <artifactId>signpost-core</artifactId>
  4. <version>1.2.1.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>oauth.signpost</groupId>
  8. <artifactId>signpost-commonshttp4</artifactId>
  9. <version>1.2.1.2</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.twitter</groupId>
  13. <artifactId>twitter-api-java-sdk</artifactId>
  14. <version>1.1.4</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>commons-httpclient</groupId>
  18. <artifactId>commons-httpclient</artifactId>
  19. <version>3.1</version>
  20. </dependency><dependency>
  21. <groupId>com.google.guava</groupId>
  22. <artifactId>guava</artifactId>
  23. <version>29.0-jre</version>
  24. </dependency>

2.相关的配置类

  1. /**
  2. * 推特相关配置
  3. */
  4. public class TwitterConfig {
  5. /**
  6. * 客户id和客户私钥
  7. */
  8. public static final String CLIENT_ID = "c3dqY111tjbnFPNDM6MTpjaQ";
  9. public static final String CLIENT_SECRET = "kf1119fmdeXZHpOV-fjv9umx55ZdccCkNONjea";
  10. /**
  11. * 应用KYE和私钥
  12. */
  13. public static final String CONSUMER_KEY = "lhyfiD111MffGeHMR";
  14. public static final String CONSUMER_SECRET = "BRNxnV5Lx111jtptduIkcwjB";
  15. /**
  16. * 应用的TOKEN
  17. */
  18. public static final String ACCESS_TOKEN = "14821111633-A8xyN5111FgkbStu";
  19. public static final String ACCESS_TOKEN_SECRET = "oZaKBphpoo111SZvzoXPAQ";
  20. /**
  21. * 用户 Bearer Token
  22. */
  23. public static final String BEARER_TOKEN = "AAAAAAAAAAAAAAAAAAAAAOwXswEAAAAAGLQE%2F%2BydboYofYWIsXeXYz%2FvwOM%3Dxyxysp8mTiT8j6feRoc0BshFaghbkC58VHMRtcdvo5WjkvyqKF";
  24. }

3.根据用户token让用户关注开发者 

  1. @Data
  2. @Accessors(chain = true)
  3. public class AttentionDto {
  4. /**
  5. * true 表示关注成功 false 表示关注失败(目标用户没有公开推文的情况,因为他们必须批准关注者请求)
  6. */
  7. private Boolean following;
  8. /**
  9. * 指示目标用户是否需要批准关注请求。请注意,只有当目标用户批准传入的关注者请求时,经过身份验证的用户才会关注目标用户 false就是正常的
  10. */
  11. private Boolean pending_follow;
  12. }
  1. /**
  2. * 用户关注
  3. * @param token 授权换取的用户token
  4. * @param userId 用户自己的ID
  5. * @return
  6. * @throws Exception
  7. */
  8. public AttentionDto attention(String token, String userId) throws Exception {
  9. String urlAdress = "https://api.twitter.com/2/users/" + userId + "/following";
  10. URL url12 = new URL(urlAdress);
  11. HttpURLConnection connection = (HttpURLConnection) url12.openConnection();
  12. connection.setRequestMethod("POST");
  13. connection.setRequestProperty("Content-Type", "application/json");
  14. connection.setRequestProperty("Authorization", "Bearer " + token);
  15. JSONObject requestBody = new JSONObject();
  16. //需要关注的用户ID
  17. requestBody.put("target_user_id", "148294855969111111");
  18. String requestBodyString = requestBody.toString();
  19. connection.setDoOutput(true);
  20. OutputStream outputStream = connection.getOutputStream();
  21. outputStream.write(requestBodyString.getBytes());
  22. outputStream.flush();
  23. outputStream.close();
  24. int responseCode = connection.getResponseCode();
  25. InputStream inputStream;
  26. if (responseCode >= 200 && responseCode < 400) {
  27. inputStream = connection.getInputStream();
  28. } else {
  29. inputStream = connection.getErrorStream();
  30. }
  31. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
  32. String line;
  33. StringBuilder responseBuilder = new StringBuilder();
  34. while ((line = reader.readLine()) != null) {
  35. responseBuilder.append(line);
  36. }
  37. reader.close();
  38. String response = responseBuilder.toString();
  39. if(JSON.parseObject(response).get("data") != null){
  40. JSONObject json = JSON.parseObject(JSON.parseObject(response).get("data").toString());
  41. AttentionDto attentionDto = new AttentionDto();
  42. Object ret = json.get("following");
  43. attentionDto.setFollowing(Boolean.parseBoolean(ret == null ? "false" : ret.toString()));
  44. ret = json.get("pending_follow");
  45. attentionDto.setPending_follow(Boolean.parseBoolean(ret == null ? "false" : ret.toString()));
  46. return attentionDto;
  47. }
  48. return null;
  49. }

4.查询我的推文列表

  1. /**
  2. * 查询我的推文列表
  3. * @param tweetUserId
  4. * @param token
  5. * @param ttTweetsId 平台指定转推文的ID
  6. * @param maxResults = 5-10之间
  7. * @return
  8. */
  9. public Integer getTweetList(String tweetUserId,String token,Integer maxResults,String ttTweetsId){
  10. try {
  11. String httpUrl = "https://api.twitter.com/2/users/"+ tweetUserId + "/tweets?max_results="+maxResults;
  12. httpUrl += "&expansions=author_id,edit_history_tweet_ids,referenced_tweets.id&tweet.fields=created_at";
  13. // 只查用户当日的推文
  14. Instant currentTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).toInstant(ZoneOffset.of("+8"));
  15. DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
  16. String endTimeRFC3339 = formatter.format(currentTime);
  17. httpUrl += "&start_time="+endTimeRFC3339;
  18. // 构建请求 URL
  19. URL url = new URL(httpUrl);
  20. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  21. // 设置请求方法和请求头
  22. connection.setRequestMethod("GET");
  23. connection.setRequestProperty("Authorization", "Bearer " + token);
  24. // 发送请求
  25. int responseCode = connection.getResponseCode();
  26. Assert.isTrue(responseCode == HttpURLConnection.HTTP_OK, "get tweet error");
  27. Integer numer = 0;
  28. // 读取响应
  29. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  30. String line;
  31. StringBuilder response = new StringBuilder();
  32. while ((line = reader.readLine()) != null) {
  33. response.append(line);
  34. }
  35. reader.close();
  36. JSONObject jsonObject = JSON.parseObject(response.toString());
  37. JSONArray jsonArray = (JSONArray) jsonObject.get("data");
  38. if(jsonArray == null){
  39. return numer;
  40. }
  41. for (int i = 0; i < jsonArray.size(); i++) {
  42. JSONObject json = jsonArray.getJSONObject(i);
  43. JSONArray referencedTweets = json.getJSONArray("referenced_tweets");
  44. if(referencedTweets != null){
  45. /*retweeted: 表示当前推文是转推(Retweet)的引用。
  46. quoted: 表示当前推文是引用推文(Quote Tweet)的引用。
  47. replied_to: 表示当前推文是回复(Reply)的引用。*/
  48. //上个推文的id
  49. String type = referencedTweets.getJSONObject(0).get("type").toString();
  50. String id = referencedTweets.getJSONObject(0).get("id").toString();
  51. if(type.equals("quoted") || type.equals("retweeted") && ttTweetsId.equals(id)){
  52. //quoted 表示推文是引用
  53. numer++;
  54. }
  55. }
  56. }
  57. // 打印响应
  58. return numer;
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. }
  62. return 0;
  63. }

5.查询那些用户进行了推文的转发

  1. /**
  2. * 根据推文ID查询那些用户进行了转发
  3. * @param tweetId
  4. * @param token
  5. * @return
  6. */
  7. public String transmitUserList(String tweetId,String token){
  8. try {
  9. // 构建请求 URL
  10. URL url = new URL("https://api.twitter.com/2/tweets/"+tweetId+"/retweeted_by");
  11. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  12. // 设置请求方法和请求头
  13. connection.setRequestMethod("GET");
  14. connection.setRequestProperty("Authorization", "Bearer " + token);
  15. // 发送请求
  16. int responseCode = connection.getResponseCode();
  17. if (responseCode == HttpURLConnection.HTTP_OK) {
  18. // 读取响应
  19. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  20. String line;
  21. StringBuilder response = new StringBuilder();
  22. while ((line = reader.readLine()) != null) {
  23. response.append(line);
  24. }
  25. reader.close();
  26. // 打印响应
  27. return response.toString();
  28. } else {
  29. System.out.println("Failed to fetch data from Twitter API. Response code: " + responseCode);
  30. }
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. return null;
  35. }

6.生成推文的访问链接

  1. /**
  2. * 生成推文转发链接
  3. * @param tweetsName 推特用户名 如:@123456
  4. * @param tweetsId 推文Id
  5. * @return
  6. */
  7. public String getTtTweetsUrl(String tweetsName,String tweetsId){
  8. //推文Id
  9. String url = "https://twitter.com/";
  10. //推特用户名
  11. url += tweetsName;
  12. url += "/status/" + tweetsId +"?s=20";
  13. return url;
  14. }

 

7.可以获取开发者的账号Bearer Token

  1. /**
  2. * 获取开发者推特token
  3. * @return
  4. */
  5. public String getTwitterToken(){
  6. try {
  7. String consumerKey = URLEncoder.encode(TwitterConfig.CONSUMER_KEY, "UTF-8");
  8. String consumerSecret = URLEncoder.encode(TwitterConfig.CONSUMER_SECRET, "UTF-8");
  9. String credentials = consumerKey + ":" + consumerSecret;
  10. String base64Credentials = Base64.getEncoder().encodeToString(credentials.getBytes());
  11. //authorization_code、refresh_token、client_credentials
  12. String grantType = "client_credentials";
  13. URL url = new URL("https://api.twitter.com/oauth2/token");
  14. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  15. connection.setRequestMethod("POST");
  16. connection.setRequestProperty("Authorization", "Basic " + base64Credentials);
  17. connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
  18. connection.setDoOutput(true);
  19. connection.setDoInput(true);
  20. String data = "grant_type=" + grantType +
  21. "&client_id="+TwitterConfig.CLIENT_ID+"&client_secret="+TwitterConfig.CLIENT_SECRET+"&code_verifier=challenge";
  22. connection.getOutputStream().write(data.getBytes("UTF-8"));
  23. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  24. StringBuilder response = new StringBuilder();
  25. String line;
  26. while ((line = reader.readLine()) != null) {
  27. response.append(line);
  28. }
  29. reader.close();
  30. // Extract bearer token from JSON response
  31. String jsonResponse = response.toString();
  32. JSONObject json = JSON.parseObject(jsonResponse);
  33. return json.get("access_token").toString();
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. return null;
  38. }

如果这篇文章在你一筹莫展的时候帮助到了你,可以请作者吃个棒棒糖

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/459971
推荐阅读
相关标签