因业务需要,需要获取指定推特的关注者名单 调用接口:https://api.twitter.com/2/users/id/followers?;
id需换成指定推特的id
private Timer timer;
private void startTimeTask() { if (null == timer) { timer = new Timer(); } timer.schedule(new TimerTask() { @Override public void run() { String url = apiPath; if (StringUtils.isNotEmpty(paginationToken) && paginationToken.length() == 16) { url = apiPath + "&pagination_token=" + paginationToken; } url += "&max_results=" + 1000; String response = getFollowers(url); if(null == response) return; Tuser user = JSON.parseObject(response, Tuser.class); List<Tdata> data = user.getData(); List<TuserPo> list = new ArrayList<>(); for (Tdata d : data) { TuserPo tuserPo = new TuserPo(); tuserPo.setId(d.getId()); tuserPo.setUsername(d.getUsername()); tuserPo.setName(d.getName()); tuserPo.setType("new"); list.add(tuserPo); } tuserPoMapper.insertList(list); log.info("insert success"); paginationToken = user.getMeta().getNext_token(); if (null == paginationToken) { TwitterInfoPo twitterInfoPo1 = new TwitterInfoPo(); twitterInfoPo1.setId(1); twitterInfoPo1.setState(2); twitterInfoPoMapper.updateByPrimaryKeySelective(twitterInfoPo1); timer.cancel(); } } }, 3000, 1000 * 60 * 2); }
private String getFollowers(String url_with_cursor) { String tweetResponse = null; HttpClient httpClient = HttpClients.custom() .setDefaultRequestConfig(RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD).build()) .build(); try { URIBuilder uriBuilder = new URIBuilder(url_with_cursor); ArrayList<NameValuePair> queryParameters = new ArrayList<>(); queryParameters.add(new BasicNameValuePair("user.fields", "username")); uriBuilder.addParameters(queryParameters); HttpGet httpGet = new HttpGet(uriBuilder.build()); httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken)); httpGet.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (null != entity) { tweetResponse = EntityUtils.toString(entity, "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } return tweetResponse; }
说明:官方API说明是15分钟频率15次,也就是1分钟1次。我这里用的是2分钟1次,加上了最大调用数1000。里面用了Mybatis存入数据库,个人可根据各自的需求进行使用,这里只有部分代码仅供参考和学习。
可以先通过postman 加 bearerToken 调用接口获取数据测试。
欢迎大家留言探讨。