镇江网站建设一般多少钱,网站内容该怎么做,虚拟主机做网站,公司网站改版 目的前面章节已经介绍使用code换取Token的整个流程了#xff0c;这里不再重复阐述了#xff0c;下面我们介绍如何使用Token查询用户信息等操作。
1.引入相关依赖Maven dependency groupIdoauth.signpost/groupId artifactIdsignpost-co… 前面章节已经介绍使用code换取Token的整个流程了这里不再重复阐述了下面我们介绍如何使用Token查询用户信息等操作。
1.引入相关依赖Maven dependency groupIdoauth.signpost/groupId artifactIdsignpost-core/artifactId version1.2.1.2/version /dependency dependency groupIdoauth.signpost/groupId artifactIdsignpost-commonshttp4/artifactId version1.2.1.2/version /dependency dependency groupIdcom.twitter/groupId artifactIdtwitter-api-java-sdk/artifactId version1.1.4/version /dependency dependency groupIdcommons-httpclient/groupId artifactIdcommons-httpclient/artifactId version3.1/version /dependencydependency groupIdcom.google.guava/groupId artifactIdguava/artifactId version29.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);ArrayListNameValuePair 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.fieldsname,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);ArrayListNameValuePair 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的话需要好好检查一下参数问题它不会给你特别明显错误的提示细节问题只能自己注意一下了。