推特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_11064 天前
C++入门基础知识133—【关于C 库函数 - asctime()】
c语言·前端·c++·微信小程序·微信公众平台·twitter·微信开放平台
怪咖学生5 天前
<meta property=“og:type“ content=“website“>
dreamweaver
tusik689 天前
Twitter网页版怎么登录?详细步骤与常见问题解答
twitter
Stanford_110612 天前
C++入门基础知识125—【关于C++ 传递指针给函数】
开发语言·前端·c++·微信小程序·微信公众平台·twitter·微信开放平台
awsless14 天前
通过 Twitter Token 实现授权与操作
javascript·爬虫·python·twitter
爱跨境的笑笑21 天前
X(twitter)推特的广告类型有哪些?怎么选择?
网络·新媒体运营·ip·twitter
Stanford_110625 天前
C++入门基础知识110—【关于C++ if...else 语句】
开发语言·前端·c++·微信小程序·微信公众平台·twitter·微信开放平台
Stanford_11061 个月前
C++入门基础知识109—【关于C++ if 语句】
开发语言·c++·微信小程序·微信公众平台·twitter·微信开放平台
Stanford_11061 个月前
C++入门基础知识99——【关于C++ 成员运算符】
开发语言·c++·微信小程序·twitter·微信开放平台
Lijunyan12981 个月前
Python、C++、java阶乘算法
python·其他·音视频·twitter·segmentfault