推特API(Twitter API)V2 查询用户信息

前面章节已经介绍使用code换取Token的整个流程了,这里不再重复阐述了,下面我们介绍如何使用Token查询用户信息等操作。

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.相关的配置类

java 复制代码
/**
 * 推特相关配置
 */
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";

}

3.查询开发者账号的推特信息

java 复制代码
public JSONObject getUserInfo(){
        //下面需要开发者门户里面的key和私钥,还包括Token和私钥
        CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(TwitterConfig.CONSUMER_KEY, TwitterConfig.CONSUMER_SECRET);
        consumer.setTokenWithSecret(TwitterConfig.ACCESS_TOKEN, TwitterConfig.ACCESS_TOKEN_SECRET);
        // 创建HttpClient对象
        HttpClient httpClient = this.setProxy();
        // 创建API请求,例如获取用户的时间线
        try {
            //请求的地址
            URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/users/me");
            ArrayList<NameValuePair> queryParameters;
            queryParameters = new ArrayList<>();
            //我们需要查询用户的那些信息
            queryParameters.add(new BasicNameValuePair("user.fields", "id,name,username,profile_image_url,public_metrics"));
            queryParameters.add(new BasicNameValuePair("expansions", "pinned_tweet_id"));
            uriBuilder.addParameters(queryParameters);
            HttpGet request = new HttpGet(uriBuilder.build());
            request.setHeader("Content-Type","application/json");
            consumer.sign(request);
            // 创建参数列表
            HttpResponse response =  httpClient.execute(request);
            // 处理API响应
            int statusCode = response.getStatusLine().getStatusCode();
            String responseBody = EntityUtils.toString(response.getEntity());
            if (statusCode == 200) {
                System.out.println(responseBody);
                return JSONObject.parseObject(responseBody);
            } else {
                System.out.println(responseBody);
                return JSONObject.parseObject(responseBody);
            }
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

4.根据用户Token查询授权用户基本信息

java 复制代码
    /**
     * 根据用户token换取用户信息
     * @return
     */
    public TwitterUserDto getUserInfoByToken(String token){
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            // Twitter API endpoint
            String endpoint = "https://api.twitter.com/2/users/me";
            // 构造带有参数的 URL
            String urlWithParams = endpoint + "?user.fields=name,pinned_tweet_id,profile_image_url";
            // 创建 URL 对象
            URL url = new URL(urlWithParams);
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("Authorization", "Bearer " + token);
            connection.setRequestProperty("Content-Type","application/json");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            TwitterUserDto dto = new TwitterUserDto();
            JSONObject json = JSONObject.parseObject(result.toString());
            JSONObject user = (JSONObject)json.get("data");
            if(user != null){
                dto.setId(user.get("id").toString());
                dto.setName(user.get("name").toString());
                dto.setUsername(user.get("username").toString());
            }
            return dto;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
java 复制代码
@Data
@Accessors(chain = true)
public class TwitterUserDto {

    /**
     * 推特名 @xxxx
     */
    private String username;

    /**
     * 推特用户名
     */
    private String name;

    /**
     * 推特用户ID
     */
    private String id;
}

5.根据用户名查询用户推特信息

java 复制代码
/**
     * 根据用户名查询用户推特数据
     * @return
     */
    public TwitterUserDto getTwitterUserByUserName(String userName){
        //推特应用里面的相关私钥和Token
        CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(TwitterConfig.CONSUMER_KEY, TwitterConfig.CONSUMER_SECRET);
        consumer.setTokenWithSecret(TwitterConfig.ACCESS_TOKEN, TwitterConfig.ACCESS_TOKEN_SECRET);
        // 创建HttpClient对象
        HttpClient httpClient = this.setProxy();
        // 创建API请求,例如获取用户的时间线
        try {
            URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/users/by");
            ArrayList<NameValuePair> queryParameters;
            queryParameters = new ArrayList<>();
            //需要查询的用户名   多个用户名称用逗号隔开(例如:张三,李四,王五   如果不行用:张三%20李四%20王五)
            queryParameters.add(new BasicNameValuePair("usernames", userName));
            queryParameters.add(new BasicNameValuePair("expansions", "pinned_tweet_id"));
            uriBuilder.addParameters(queryParameters);
            HttpGet request = new HttpGet(uriBuilder.build());
            request.setHeader("Content-Type","application/json");
            consumer.sign(request);
            // 创建参数列表
            HttpResponse response =  httpClient.execute(request);
            // 处理API响应
            int statusCode = response.getStatusLine().getStatusCode();
            String responseBody = EntityUtils.toString(response.getEntity());
            if (statusCode == 200) {
                TwitterUserDto dto = new TwitterUserDto();
                JSONObject json = JSONObject.parseObject(responseBody);
                JSONArray user = (JSONArray)json.get("data");
                if(user != null){
                    json = (JSONObject)user.get(0);
                    dto.setId(json.get("id").toString());
                    dto.setName(json.get("name").toString());
                    dto.setUsername(json.get("username").toString());
                }
                return dto;
            } else {
                return null;
            }
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


 /**
     * 设置请求代理
     * @param
     * @return
     */
    private HttpClient setProxy(){
        // 创建HttpClientBuilder对象
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        HttpClient client = httpClientBuilder.build();;
        return client;
    }

注意事项:如果推特报401的话请检查Token是否过期,如果报400的话需要好好检查一下参数问题,它不会给你特别明显错误的提示,细节问题只能自己注意一下了。

相关推荐
Stanford_11065 小时前
高级的SQL查询技巧有哪些?
sql·微信小程序·twitter·微信开放平台
freewind4 天前
如何高效获取Twitter数据:Apify平台上的推特数据采集解决方案
twitter
130252015127 天前
哪些视频媒体平台可给企业直播间做分发拉流转播宣传?提升流量数据!
音视频·媒体·twitter
Stanford_110622 天前
什么是人工智能大模型?
c++·人工智能·微信小程序·微信公众平台·twitter·微信开放平台
Stanford_110623 天前
关于IDE的相关知识之三【插件安装、配置及推荐的意义】
c++·ide·微信小程序·微信公众平台·twitter·微信开放平台
Stanford_110624 天前
C++游戏开发入门:如何从零开始实现自己的游戏项目?
c++·游戏·微信小程序·c·微信公众平台·twitter·微信开放平台
wangye1142224 天前
国外媒体发布新闻稿/海外媒体网站发稿创历史新潮流
人工智能·twitter
Stanford_11061 个月前
关于IDE的相关知识之一【使用技巧】
前端·ide·windows·微信小程序·微信公众平台·twitter·微信开放平台
Stanford_11061 个月前
用c++做游戏开发至少要掌握哪些知识?
开发语言·c++·微信小程序·c·微信公众平台·twitter·微信开放平台
Stanford_11061 个月前
C++入门基础知识150—【关于C++ 输入/输出运算符重载】
前端·javascript·c++·微信小程序·微信公众平台·twitter·微信开放平台