java实现新浪oauth2.0获取用户信息并发表一条微博

刚刚工作……….

工作中用到了新浪微博的oauth , 因为用到的功能不多,并没有用新浪的SDK,都是自己写的,没有考虑大多数的异常处理。

oauth验证过程不再叙述。
用到了struts2。

引导用户到授权界面当用户在网站上点击用新浪微博登陆后的执行过程。


 public String authWeiboSignIn()
{
    authorizationURL = "https://api.weibo.com/oauth2/authorize?client_id="+appKEY+"&response_type=code&redirect_uri=callbackURL";
    return SUCCESS;
}

struts2的xml配置


<action name="weiboSinaSignIn" class="com.tech.action.SinaAction"
        method="authWeiboSignIn">
        <result name="success" type="redirect">${authorizationURL}</result>
</action>

用户授权完成后会返回code,这个code是以后所有操作的钥匙,通过code可以获得accessToken和uid ,uid和accessToken就是访问新浪API的凭证。
用户同意授权后,根据redirect_uri可以重新返回。我在redirect_uri中配置了要请求的action,流程就转到了action所配置的方法。
redirect_uri返回的action配置


<action name="weiboLogin" class="com.tech.action.SinaAction"
        method="weiboLogin">
<action/>

方法中获取请求后的code,让后用http post请求获取accessToken和uid


public String weiboLogin() {
    HttpServletRequest request = ServletActionContext.getRequest();
    String code = request.getParameter("code");
    Map<String, String> token = this.getAccessTokenAndUid(code);
}
/**
 * 获取accestoken和用户在新浪微博的uid
 * @param code 获取accessToken的钥匙
 * @return
 */
private Map<String , String> getAccessTokenAndUid(String code){
    String responseDate = "" ;
    Map<String , String> token = new HashMap<String, String>();
            //本机运行时会报证书错误
    /*ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
    Protocol.registerProtocol("https", new Protocol("https", fcty, 443));*/
    PostMethod postMethod = new PostMethod("https://api.weibo.com/oauth2/access_token");
    postMethod.addParameter("grant_type", "authorization_code");
    postMethod.addParameter("code",code);
    postMethod.addParameter("redirect_uri","callBackURL");
    postMethod.addParameter("client_id",KEY);
    postMethod.addParameter("client_secret",appSECRET);
    HttpClient client = new HttpClient();
    try {
        client.executeMethod(postMethod);
        responseDate = postMethod.getResponseBodyAsString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if(!responseDate.equals("") && responseDate.indexOf("access_token") != -1){
        JSONObject jsonData = JSONObject.fromObject(responseDate);
        token.put("accessToken", (String)jsonData.get("access_token"));
        token.put("uid", jsonData.getString("uid"));
    }
    return  token;
}

现在的map结合中存储了accessToken和uid , 就能取得授权用户的信息了。这里我只需要微博名称和用户的头像地址。


public String weiboLogin() {
    HttpServletRequest request = ServletActionContext.getRequest();
    String code = request.getParameter("code");
    Map<String, String> token = this.getAccessTokenAndUid(code);
    Map<String , String> userInfo = this.getUserWeiBoInfo(token);
}


private Map<String , String> getUserWeiBoInfo(Map<String , String> token){
    Map<String , String> userData = new HashMap<String, String>();
    String UserInfo = "";
    String url = "https://api.weibo.com/2/users/show.json?access_token="+token.get("sinaUid")"&uid="+token.get("sinaAccessToken");
    GetMethod getMethod = new GetMethod(url);
    HttpClient client = new HttpClient();
    try {
        client.executeMethod(getMethod);
        UserInfo = getMethod.getResponseBodyAsString();
        JSONObject jsonData = JSONObject.fromObject(UserInfo);
        userData.put("name",jsonData.getString("name").toString() );
        userData.put("headImg", jsonData.getString("profile_image_url"));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return userData;
}

在授权用户中发表一篇微博:


public String weiboLogin() {
    HttpServletRequest request = ServletActionContext.getRequest();
    String code = request.getParameter("code");
    Map<String, String> token = this.getAccessTokenAndUid(code);
    Map<String , String> userInfo = this.getUserWeiBoInfo(token);
    this.shareToSina(token);
}
private void shareToSina(Map<String , String>) throws IllegalArgumentException, HttpException, IOException
{
    /*ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
    Protocol.registerProtocol("https", new Protocol("https", fcty, 443));*/
    PostMethod postMethod = new PostMethod("https://api.weibo.com/2/statuses/update.json");
    postMethod.addParameter("access_token", token.get("sinaAccessToken"));
    postMethod.addParameter("status","发表一条微博");
    HttpMethodParams param = postMethod.getParams();
    param.setContentCharset("UTF-8");
    HttpClient client = new HttpClient();
    client.executeMethod(postMethod);
    postMethod.getResponseBodyAsString();
}

你可能感兴趣的:(java,新浪oauth2.0)