前面章节已经介绍使用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的话需要好好检查一下参数问题,它不会给你特别明显错误的提示,细节问题只能自己注意一下了。