新浪微博自动获取access_token问题

kkyxzy 2016-02-18 09:59:27

package weibo4j.examples.timeline;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import weibo4j.Oauth;
import weibo4j.Timeline;
import weibo4j.http.AccessToken;
import weibo4j.model.WeiboException;
import weibo4j.util.WeiboConfig;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class sinaWeiBoUL {
/***
* 模拟登录并得到登录后的Token
* @param username 用户名
* @param password 密码
* @return
* @throws HttpException
* @throws IOException
*/
public static AccessToken getToken(String username,String password) throws HttpException, IOException{
String clientId = WeiboConfig.getValue("client_ID") ;
String redirectURI = WeiboConfig.getValue("redirect_URI") ;
String url = WeiboConfig.getValue("authorizeURL");

PostMethod postMethod = new PostMethod(url);
//应用的App Key
postMethod.addParameter("client_id",clientId);
//应用的重定向页面
postMethod.addParameter("redirect_uri",redirectURI);
//模拟登录参数
//开发者或测试账号的用户名和密码
postMethod.addParameter("userId", username);
postMethod.addParameter("passwd", password);
postMethod.addParameter("isLoginSina", "0");
postMethod.addParameter("action", "submit");
postMethod.addParameter("response_type","code");
HttpMethodParams param = postMethod.getParams();
param.setContentCharset("UTF-8");
//添加头信息
List<Header> headers = new ArrayList<Header>();
headers.add(new Header("Referer", "https://api.weibo.com/oauth2/authorize?client_id="+clientId+"&redirect_uri="+redirectURI+"&from=sina&response_type=code"));
headers.add(new Header("Host", "api.weibo.com"));
headers.add(new Header("User-Agent","Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"));
HttpClient client = new HttpClient();
client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
client.executeMethod(postMethod);
int status = postMethod.getStatusCode();
System.out.println(status);
if (status != 302)
{
System.out.println("token刷新失败");
return null;
}
//解析Token
Header location = postMethod.getResponseHeader("Location");
if (location != null)
{
String retUrl = location.getValue();
int begin = retUrl.indexOf("code=");
if (begin != -1) {
int end = retUrl.indexOf("&", begin);
if (end == -1)
end = retUrl.length();
String code = retUrl.substring(begin + 5, end);
if (code != null) {
Oauth oauth = new Oauth();
try{
AccessToken token = oauth.getAccessTokenByCode(code);
return token;
}catch(Exception e){
e.printStackTrace();
}
}
}
}
return null;
}
/**
* 发微博
* @param token 认证Token
* @param content 微博内容
* @return
* @throws Exception
*/
public static boolean sinaSendWeibo(String token,String content) throws Exception {
boolean flag = false ;
Timeline timeline = new Timeline();
timeline.client.setToken(token);
try
{
timeline.UpdateStatus(content);
flag = true ;
}
catch (WeiboException e)
{
flag = false ;
System.out.println(e.getErrorCode());
}
return flag;
}


public static void main(String[] args) throws Exception
{
AccessToken at = getToken("用户","密码");
System.out.println(at.getAccessToken());
sinaSendWeibo(at.getAccessToken(),"测试呢");
}
}

使用该代码报
200
token刷新失败
Exception in thread "main" java.lang.NullPointerException
at weibo4j.examples.Sina.main(Sina.java:114)求问如何解决
...全文
518 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
shiping8000 2018-06-12
  • 打赏
  • 举报
回复
两年前的问题了 不知道今年解决没有 急求
Sydnie小猫猫 2016-12-27
  • 打赏
  • 举报
回复
引用 3 楼 a276202031 的回复:
竟然挖坟
怎样?有没有解决?
浮云若水 2016-12-27
  • 打赏
  • 举报
回复
竟然挖坟
Sydnie小猫猫 2016-12-27
  • 打赏
  • 举报
回复
我也遇到了相同的问题,楼主解决了吗?
kkyxzy 2016-02-18
  • 打赏
  • 举报
回复
没人回答吗?
weibo node sdk 是新浪微博 Node.js SDK。 特点 api可配置化 接口采用promise 最少依赖,专注新浪微博OAuth2.0认证 使用方法 安装 npm install iweibo 配置 引入iweibo var iweibo = require('iweibo'); var Weibo = iweibo.Weibo; 配置app信息 iweibo.set(name, options); //设置单条 iweibo.set(optionsObject);  //设置多条 iweibo.set({  appkey: 'xxx',  appsecret: 'xxxxxxxxxx'  }) 支持的配置: var CONFIG = {  appkey: '',  appsecret: '',  oauth_host: 'https://api.weibo.com/oauth2/authorize',  access_url: 'https://api.weibo.com/oauth2/access_token',  api_url: 'https://api.weibo.com/2/'  } 配置api接口 iweibo.setAPI(apiname, options); //设置单条api iweibo.setAPI(optionsObject);  //设置多条api iweibo.setAPI('statuses/update', {  method: 'post',  params: {  status: 'hello, world',  visible: 0  } }); 配置下微博接口(由于太多,并且不时更新,所以我就没全配置),配置下自己使用的接口,方法参考下件,基本如下: '接口名称': {  method: 'get', //请求方法,post或者get(get可省略),参考api文档  params: { //默认参数,不用填写appkey和access_token,程序会自动补上  } } 可以讲接口统一写到一个json或者js文件中,然后使用 require 引入,直接给 setAPI 传入 使用 参考 examples/app.js 文件(需要先在本目录执行 npm install 安装依赖模块) 修改host,添加下面内容: 127.0.0.1 testapp.cn 进入 open.weibo.com 设置应用回调地址到 http://testapp.cn/callbak 获取登录链接 weibo.getAuthorizeURL(backURL); 获取access_token weibo.getAccessToken('code', {  code: code,  redirect_uri: backURL }).done(function(err, data) {  var realpath = templateDir   'callback.html';  html = fs.readFileSync(realpath);  data = JSON.parse(data);  data.refresh_token = data.refresh_token || '';  req.session.refresh_token = data.refresh_token;  req.session.access_token = data.access_token;  req.session.uid = data.uid;  html = bdTemplate(html, data);  res.end(html); }).fail(function(err, data) {  var html;  if (err) {  html = fs.readFileSync(templateDir   'error.html');  }      res.end(html); }); 使用api接口 //所有API都支持promise接口  weibo.api('users/show', urlObj).done(function(err, result) {  console.log(result);  res.end(JSON.stringify(result));  }); 测试方法 进入examples 修改config.json,回调地址需要在open.weibo.com配置好,然后修改自己的host,将回调地址指到127.0.0.1 执行 npm install 访问自己在config.json配置的网站 标签:weibo
为什么需要另外一个Java版本的微博客户端? 新浪微博官方推荐的Java客户端 weibo4j 一直没有发布到maven仓库,而我们是重度maven用户,因而重新发明了这个新的轮子。 通过maven引用weiboclient4j 在项目pom.xml里面加入依赖:  com.github.hoverruan weiboclient4j 0.4.13 使用 Weiboclient4j支持新浪微博API V1和V2(未完成),目前推荐使用V2版本的接口: // 使用你的应用的api key和secret String apiKey = "xxxxxxx";  String apiSecret = "xxxxxxxx";  WeiboClient client = new WeiboClient(apiKey, apiSecret); OAuth2例子: String authorizationCallback = "..."; // 你的Callback地址  String state = "...";  String url = client.getAuthorizationUrl(ResponseType.Code, DisplayType.Default, state, authorizationCallback); // 浏览器重定向到url; 用户授权; 然后返回callback地址  String code = ... // 从新浪的回调请求里面获得code String accessTokenCallback = "..."; // 或者Access Token的Callback地址  SinaWeibo2AccessToken accessToken = client.getAccessTokenByCode(code, accessTokenCallback);  System.out.println("Access token: "   accessToken.getToken());  System.out.println("User Uid: "   accessToken.getUid());  System.out.println("Expires in: "   accessToken.getExpiresIn());  System.out.println("Remind in: "   accessToken.getRemindIn()); 获取用户Timeline例子: StatusService service = client.getStatusService();  Timeline friendsTimeline = service.getFriendsTimeline(); 更多的使用例子可以参考 weiboclient4j.examples.OAuth2CommandLine API参数对象化 WeiboClient里面,大部分的方法都没有Javadoc,取而代之的是大部分的参数都是特定的对象,这样做的原因是因为: 写Javadoc太麻烦 一些API的参数较多,如果使用基本类型容易混淆各个参数的含义 IDE对已知类型的对象、Enum能提供更友好的提醒和自动完成 所有的参数对象在 package weiboclient4j.params 下面;举一个例子: 使用静态引入 CoreParameters.\*: import static weiboclient4j.params.CoreParameters.*;  FriendshipService service = client.getFriendshipService();  Friendship friendship;  friendship = service.getFriendship(sourceUid(12345), targetUid(67890));  // 或者  friendship = service.getFriendship(sourceScreenName("xxx"), targetScreenName("yyy")); 使用 P: import weiboclient4j.params.P;  FriendshipService service = client.getFriendshipService();  Friendship friendship;  friendship = service.getFriendship(P.sourceUid(12345), P.targetUid(67890));  // 或者  friendship = service.getFriendship(P.sourceScreenName("xxx"), P.targetScreenName("yyy")); 分页对象 Paging 分页相关的参数,全部通过 Paging 对象封装: Paging paging = Paging.create() .sinceId(12345) .count(25);  Timeline timeline = service.getFriendsTimeline(paging, BaseApp.No, Feature.All); // 后两个参数可省略 新浪微博API V2支持情况 API文档 V2 微博接口 StatusService 完成 评论接口 CommentService 完成 用户接口 UserService 完成 关系接口 FriendshipService 完成 帐号接口 AccountService 完成 收藏接口 FavoriteService 完成 话题接口 TrendService 完成 标签接口 TagService 完成 注册接口 RegisterService 完成 搜索接口 SearchService 完成 推荐接口 SuggestionService 完成 提醒接口 RemindService 完成 短链接口 ShortUrlService 完成 通知接口 NotificationService 完成 公共服务接口 CommonService 完成 位置服务接口 PlaceService 完成 地理信息接口 LocationService 开发中

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧