Twitter REST api - 通过主题标签访问推文

Twitter REST api - access tweets by hashtag

这是我编写的代码,用于使用 Twitter REST 服务访问给定用户的推文:

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

public class GetTweets {


    private static final String BEARER_TOKEN = "test";

    public static String getTweetsByUsername(final String username) {
        final ObjectMapper objectMapper = new ObjectMapper();

        try {
            URL url = new URL("https://api.twitter.com/2/users/by/username/" + username);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            final DataResponse dataResponse = objectMapper.readValue(content.toString(), DataResponse.class);

            url = new URL("https://api.twitter.com/2/users/" + dataResponse.getUserDetails().getId() + "/tweets");
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "None";
    }

    public static void main(String argsp[]) throws IOException {

        List<String> users = Arrays.asList("test1" , "test2");

        users.forEach(x -> {

                System.out.println(GetTweets.getTweetsByUsername(x));

        });

    }
}

这符合预期我不确定如何找到给定主题标签的推文。

例如,如果我使用:

 List<String> users = Arrays.asList("#test1");

我收到异常:

java.io.FileNotFoundException: https://api.twitter.com/2/users/by/username/#test1

通过主题标签访问推文的端点路径是什么?我试过 https://api.twitter.com/2/users/by/hashtag/#test1 但这个不存在。

这里有一个类似的问题 Twitter REST API: tweet extraction 但这指的是 api 的早期版本。

Search tweets doc

Search query syntax

我无法访问 Twitter API 但文档说它应该可以工作:

https://api.twitter.com/2/tweets/search/recent?query=#test

采用@Egor 提供的答案,并对其进行增强以包含您的其他要求,以查找来自带有主题标签的特定用户的推文,您可以在查询中使用 from: 语法,并结合主题标签本身。

https://api.twitter.com/2/tweets/search/recent?query=#test1%20from:user1