????????前面章節已經介紹使用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.相關的配置類
/*** 推特相關配置*/
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.查詢開發者賬號的推特信息
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查詢授權用戶基本信息
/*** 根據用戶token換取用戶信息* @return*/public TwitterUserDto getUserInfoByToken(String token){StringBuilder result = new StringBuilder();BufferedReader in = null;try {// Twitter API endpointString endpoint = "https://api.twitter.com/2/users/me";// 構造帶有參數的 URLString 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;}
@Data
@Accessors(chain = true)
public class TwitterUserDto {/*** 推特名 @xxxx*/private String username;/*** 推特用戶名*/private String name;/*** 推特用戶ID*/private String id;
}
5.根據用戶名查詢用戶推特信息?
/*** 根據用戶名查詢用戶推特數據* @return*/public TwitterUserDto getTwitterUserByUserName(String userName){//推特應用里面的相關私鑰和TokenCommonsHttpOAuthConsumer 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的話需要好好檢查一下參數問題,它不會給你特別明顯錯誤的提示,細節問題只能自己注意一下了。