一、 开发前准备
1 注册新浪微博
2 访问新浪微博开发平台http://open.weibo.com,如果是企业,申请企业接入,并提交相关资料进行审核;如果是个人开发者,就请申请个人开发者应用,以下以开发者为例
3 进入http://open.weibo.com/,鼠标放在微连接上,点击站内应用,然后就开始创建应用。按照步骤填写即可。填写完毕,提交申请,只要提交了就可测试。具体信息如下
4 https://github.com/sunxiaowei2014/weibo4j-oauth2-beta3.1.1/ 下载JAVA版本SDK
5 打开sdk的config.properties,将应用的appkey和appsecret对应写入client_ID和client_SERCRET,redirect_URI的值是我们创建应用中”应用实际地址”
二、 授权
1 运行OAuth4Code,如果弹出页面为下图,说明应用中写的”应用实际地址”与config.properties的redirect_URI不一致.
填写正确后,应弹出下列界面:
三、 获取用户信息,内容同步:
(微博api在线文档 http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI)
package com.wingo.action.config;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import weibo4j.Account;
import weibo4j.Oauth;
import weibo4j.Timeline;
import weibo4j.Users;
import weibo4j.model.Status;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;
public class SinaLoginAction {
static Logger log = Logger.getLogger(SinaLoginAction.class.getName());
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
public String test(){
response.setContentType("text/html;charset=UTF-8");
String code = request.getParameter("code");
Oauth oauth = new Oauth();
String access_token;
try {
System.out.println("---------------------------------");
access_token = oauth.getAccessTokenByCode(code).getAccessToken();
Account account = new Account(access_token);
JSONObject jsonObject = account.getUid();
String uid;
try {
uid = Long.toString((Long)jsonObject.get("uid"));
User user =new Users(access_token).showUserById(uid);
System.out.println("授权用户的名称:"+user.getScreenName());
System.out.println("用户最后一条微博:"+user.getStatus());
/**
* 测试发布一条新微博,微博内容不可超过140个汉字
*/
Timeline timeline = new Timeline(access_token);
Status status = timeline.updateStatus("LEO测试转发微博是否成功");
System.out.println("转发的微博:"+status);
return null;
} catch (JSONException e) {
e.printStackTrace();
}
} catch (WeiboException e) {
if(401 == e.getStatusCode()){
log.info("Unable to get the access token");;
}else{
e.printStackTrace();
}
}
return null;
}
}
备注:运行OAuth4Code后会回调redirect_uri,我的redirect_uri就是我上面sinaLoginAction的test方法。可根据业务需求进行改变。