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

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

1.引入相关依赖Maven

<dependency>
    <groupId>oauth.signpost</groupId>
    <artifactId>signpost-core</artifactId>
    <version>1.2.1.2</version>
</dependency>

<dependency>
    <groupId>oauth.signpost</groupId>
    <artifactId>signpost-commonshttp4</artifactId>
    <version>1.2.1.2</version>
</dependency>

<dependency>
    <groupId>com.twitter</groupId>
    <artifactId>twitter-api-java-sdk</artifactId>
    <version>1.1.4</version>
</dependency>

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency><dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>29.0-jre</version>
</dependency>

2.相关的配置类

/**
 * 推特相关配置
 */
public class TwitterConfig {
 
    /**
     * 客户id和客户私钥
     */
    public static final String CLIENT_ID = "c3dqY111tjbnFPNDM6MTpjaQ";
    public static final String CLIENT_SECRET = "kf1119fmdeXZHpOV-fjv9umx55ZdccCkNONjea";
 
 
    /**
     * 应用KYE和私钥
     */
    public static final String CONSUMER_KEY = "lhyfiD111MffGeHMR";
    public static final String CONSUMER_SECRET = "BRNxnV5Lx111jtptduIkcwjB";
 
    /**
     * 应用的TOKEN
     */
    public static final String ACCESS_TOKEN = "14821111633-A8xyN5111FgkbStu";
    public static final String ACCESS_TOKEN_SECRET = "oZaKBphpoo111SZvzoXPAQ";
 
        /**
     * 用户 Bearer Token
     */
    public static final String BEARER_TOKEN = "AAAAAAAAAAAAAAAAAAAAAOwXswEAAAAAGLQE%2F%2BydboYofYWIsXeXYz%2FvwOM%3Dxyxysp8mTiT8j6feRoc0BshFaghbkC58VHMRtcdvo5WjkvyqKF";
 
}

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

@Data
@Accessors(chain = true)
public class AttentionDto {

    /**
     * true 表示关注成功  false 表示关注失败(目标用户没有公开推文的情况,因为他们必须批准关注者请求)
     */
    private Boolean following;

    /**
     * 指示目标用户是否需要批准关注请求。请注意,只有当目标用户批准传入的关注者请求时,经过身份验证的用户才会关注目标用户  false就是正常的
     */
    private Boolean pending_follow;

}
  /**
     * 用户关注
     * @param token 授权换取的用户token
     * @param userId 用户自己的ID
     * @return
     * @throws Exception
     */
    public AttentionDto attention(String token, String userId) throws Exception {
        String urlAdress = "https://api.twitter.com/2/users/" + userId + "/following";
        URL url12 = new URL(urlAdress);
        HttpURLConnection connection = (HttpURLConnection) url12.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + token);
        JSONObject requestBody = new JSONObject();
        //需要关注的用户ID
        requestBody.put("target_user_id", "148294855969111111");
        String requestBodyString = requestBody.toString();
        connection.setDoOutput(true);
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(requestBodyString.getBytes());
        outputStream.flush();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        InputStream inputStream;
        if (responseCode >= 200 && responseCode < 400) {
            inputStream = connection.getInputStream();
        } else {
            inputStream = connection.getErrorStream();
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder responseBuilder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            responseBuilder.append(line);
        }
        reader.close();
        String response = responseBuilder.toString();
        if(JSON.parseObject(response).get("data") != null){
            JSONObject json = JSON.parseObject(JSON.parseObject(response).get("data").toString());
            AttentionDto attentionDto = new AttentionDto();
            Object ret = json.get("following");
            attentionDto.setFollowing(Boolean.parseBoolean(ret == null ? "false" : ret.toString()));
            ret = json.get("pending_follow");
            attentionDto.setPending_follow(Boolean.parseBoolean(ret == null ? "false" : ret.toString()));
            return attentionDto;
        }
        return null;
    }

4.查询我的推文列表

 /**
     * 查询我的推文列表
     * @param tweetUserId
     * @param token
     * @param ttTweetsId  平台指定转推文的ID
     * @param maxResults = 5-10之间
     * @return
     */
    public Integer getTweetList(String tweetUserId,String token,Integer maxResults,String ttTweetsId){
        try {
            String httpUrl = "https://api.twitter.com/2/users/"+ tweetUserId + "/tweets?max_results="+maxResults;
            httpUrl += "&expansions=author_id,edit_history_tweet_ids,referenced_tweets.id&tweet.fields=created_at";
            // 只查用户当日的推文
            Instant currentTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).toInstant(ZoneOffset.of("+8"));
            DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
            String endTimeRFC3339 = formatter.format(currentTime);
            httpUrl += "&start_time="+endTimeRFC3339;
                // 构建请求 URL
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法和请求头
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Bearer " + token);
            // 发送请求
            int responseCode = connection.getResponseCode();
            Assert.isTrue(responseCode == HttpURLConnection.HTTP_OK, "get tweet error");
            Integer numer = 0;
            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            JSONObject jsonObject = JSON.parseObject(response.toString());
            JSONArray jsonArray = (JSONArray) jsonObject.get("data");
            if(jsonArray == null){
                return numer;
            }
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                JSONArray referencedTweets = json.getJSONArray("referenced_tweets");
                if(referencedTweets != null){
                        /*retweeted: 表示当前推文是转推(Retweet)的引用。
                        quoted: 表示当前推文是引用推文(Quote Tweet)的引用。
                        replied_to: 表示当前推文是回复(Reply)的引用。*/
                    //上个推文的id
                    String type = referencedTweets.getJSONObject(0).get("type").toString();
                    String id = referencedTweets.getJSONObject(0).get("id").toString();
                    if(type.equals("quoted") || type.equals("retweeted") && ttTweetsId.equals(id)){
                        //quoted 表示推文是引用
                        numer++;
                    }
                }
            }
            // 打印响应
            return numer;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

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

/**
     * 根据推文ID查询那些用户进行了转发
     * @param tweetId
     * @param token
     * @return
     */
    public String transmitUserList(String tweetId,String token){
        try {
            // 构建请求 URL
            URL url = new URL("https://api.twitter.com/2/tweets/"+tweetId+"/retweeted_by");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法和请求头
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Bearer " + token);

            // 发送请求
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                // 打印响应
                return response.toString();
            } else {
                System.out.println("Failed to fetch data from Twitter API. Response code: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

6.生成推文的访问链接

    /**
     * 生成推文转发链接
     * @param tweetsName   推特用户名   如:@123456
     * @param tweetsId     推文Id
     * @return
     */
    public String getTtTweetsUrl(String tweetsName,String tweetsId){
        //推文Id
        String url = "https://twitter.com/";
        //推特用户名
        url += tweetsName;
        url += "/status/" + tweetsId +"?s=20";
        return url;
    }

 

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

/**
     * 获取开发者推特token
     * @return
     */
    public String getTwitterToken(){
        try {
            String consumerKey = URLEncoder.encode(TwitterConfig.CONSUMER_KEY, "UTF-8");
            String consumerSecret = URLEncoder.encode(TwitterConfig.CONSUMER_SECRET, "UTF-8");
            String credentials = consumerKey + ":" + consumerSecret;
            String base64Credentials = Base64.getEncoder().encodeToString(credentials.getBytes());
            //authorization_code、refresh_token、client_credentials
            String grantType = "client_credentials";
            URL url = new URL("https://api.twitter.com/oauth2/token");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Basic " + base64Credentials);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            String data = "grant_type=" + grantType +
                "&client_id="+TwitterConfig.CLIENT_ID+"&client_secret="+TwitterConfig.CLIENT_SECRET+"&code_verifier=challenge";
            connection.getOutputStream().write(data.getBytes("UTF-8"));

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // Extract bearer token from JSON response
            String jsonResponse = response.toString();
            JSONObject json = JSON.parseObject(jsonResponse);
            return json.get("access_token").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

如果这篇文章在你一筹莫展的时候帮助到了你,可以请作者吃个棒棒糖🙂,如果有啥疑问或者需要完善的地方欢迎大家在下面留言或者私信作者优化改进。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值