`
longzhun
  • 浏览: 360167 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

腾讯微博Oauth2.0授权以及API调用封装

 
阅读更多

 

说明:大家看到引用的包中有weibo2这个路径,这是我自己修改的,因为我的项目中有1.0的包,冲突了

上一篇讲sina的封装看到的webbo5j也是因为冲突才改的,希望大家不要误解


TuanDistributedHttpSession 这是封装的分布式session

MyUser  这是封装的一个User对象

 

 

腾讯提供的sdk中有代码错误,给大家看看

这是我修改过的,没修改之前是OAuthVersion == OAuthConstants.OAUTH_VERSION_1

这是一个小问题,估计也是刚毕业的写的

我在附件中会提供修改过的Jar包,直接用就行

public BasicAPI(String OAuthVersion){
        if (OAuthVersion.equals(OAuthConstants.OAUTH_VERSION_1 )) {
            requestAPI = new OAuthV1Request();
            apiBaseUrl=APIConstants.API_V1_BASE_URL;
        }else if(OAuthVersion.equals(OAuthConstants.OAUTH_VERSION_2_A)){
            requestAPI = new OAuthV2Request();
            apiBaseUrl=APIConstants.API_V2_BASE_URL;
        }
    }

 

 

 


 package com.tuan.web.service.weibo;    

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.tencent.weibo2.api.FriendsAPI;
import com.tencent.weibo2.api.TAPI;
import com.tencent.weibo2.api.UserAPI;
import com.tencent.weibo2.oauthv2.OAuthV2;
import com.tencent.weibo2.oauthv2.OAuthV2Client;
import com.tencent.weibo2.utils.QHttpClient;

/** 
 * @Title: QQWeiBo2.java
 * @Package com.tuan.web.service.weibo
 * @Description: TODO(腾讯微博)
 * @author longzhun
 * @date 2012-7-30 上午09:36:00
 * @version V2.0
 */
@Service
public class QQWeiBo2 {
    private static final Log LOG = LogFactory.getLog(QQWeiBo2.class);
   
    private OAuthV2 oAuth;
   
    public QQWeiBo2(){
        oAuth=new OAuthV2();
        init();
    }
   

    public String getRequestToken(){
         String authorizationUrl = "";
         QHttpClient qHttpClient=new QHttpClient(2, 2, 5000, 5000, null, null);
         OAuthV2Client.setQHttpClient(qHttpClient);
         authorizationUrl = OAuthV2Client.generateAuthorizationURL(oAuth);
         return authorizationUrl;
    }
    public OAuthV2 getAccessToken(OAuthV2 oAuth,String code,String openid,String openkey){
            //检查是否正确取得授权码
           if (oAuth.getStatus() == 2) {
               LOG.error("Get Authorization Code failed!");
           }
          
           //换取access token
           oAuth.setGrantType("authorize_code");
          
           try {
               OAuthV2Client.setAuthorization(code, openid, openkey, oAuth);
               OAuthV2Client.accessToken(oAuth);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
           //检查是否正确取得access token
           if (oAuth.getStatus() == 3) {
               LOG.error("Get Access Token failed!");
            }
           return oAuth;
    }
   
    public void pulishMsg(OAuthV2 oAuth,String status,String fileName) throws Exception{
            TAPI tAPI=new TAPI(oAuth.getOauthVersion());//根据oAuth配置对应的连接管理器
            if(StringUtils.isBlank(fileName)){
                 tAPI.add(oAuth, "json", status, "127.0.0.1");
            }else{
                tAPI.addPic(oAuth, "json", status, "127.0.0.1", fileName);   //发布围脖
            }
            tAPI.shutdownConnection();
    }
    public void createFriend(OAuthV2 oAuth,String name) throws Exception{
        FriendsAPI friendsAPI= new FriendsAPI(oAuth.getOauthVersion());
        String checkData = friendsAPI.check(oAuth, "json", name, "", "2");
        JSONObject responseJsonObject;
        JSONObject dataJsonObject;
        responseJsonObject= JSONObject.fromObject(checkData);
        dataJsonObject=((JSONObject)responseJsonObject.get("data"));
        String isidol = ((JSONObject)dataJsonObject.get(name)).get("isidol").toString();
        if("false".equals(isidol)){
           friendsAPI.add(oAuth, "json", name, "");   //添加关注
        }
        friendsAPI.shutdownConnection();
    }
   
    public MyUser getUserInfo(OAuthV2 oAuth,String name) throws Exception{
         UserAPI userAPI= new UserAPI(oAuth.getOauthVersion());
         String res = null;
         weibo4j.org.json.JSONObject userData = null;
         MyUser user = null;
         if(StringUtils.isBlank(name)){
             res = userAPI.info(oAuth, "json");
         }else{
             res =  userAPI.infos(oAuth, "json", name, "");
         }
         weibo4j.org.json.JSONObject userJson = new weibo4j.org.json.JSONObject(res);
         userData = userJson.getJSONObject("data");
         System.out.println(userData);
            if (userData != null){
                user = new MyUser();
                user.setId(userData.getString("openid"));
                user.setUserName(userData.getString("name"));
                user.setHuaming(userData.getString("nick"));
                user.setLocation(userData.getString("location"));
                user.setBirth(userData.getString("birth_year"));
                user.setDescription(userData.getString("introduction"));
                String head = userData.getString("head");
                if (head != null && !"".equals(head))
                    user.setPicUrl((new StringBuilder(String.valueOf(userData.getString("head")))).append("/50").toString());
                String sex = userData.getString("sex");
                if (sex != null && !"".equals(sex))
                    user.setSex(Integer.valueOf(Integer.parseInt(sex)));
            }
         userAPI.shutdownConnection();
         return user;
    }

   //ClientId,ClientSecret  大家自己去申请,这个我改动了 不能给大家用
    public void init(){
        oAuth.setClientId("801187117");
        oAuth.setClientSecret("2d485d1c588849ca036452d78ad82bc4");
        oAuth.setRedirectUri("http://www.55tuan.com/a/forwardQQweibo2.do");
    }


    public OAuthV2 getOAuth() {
   
        return oAuth;
    }


    public void setOAuth(OAuthV2 auth) {
   
        oAuth = auth;
    }
   
   
}

 

 

    @RequestMapping(value = "/bindQQ2",method=RequestMethod.GET)
    public String bindQQ2(QueryForm queryForm, String goodsId,ModelMap modelMap, HttpServletRequest request,
            HttpServletResponse response) {
        String authorizationUrl = "";
        try{
           
            authorizationUrl = qqWeiBo2.getRequestToken();
            TuanDistributedHttpSession session = new TuanDistributedHttpSession(request, response);
            session.setAttribute("oAuth", qqWeiBo2.getOAuth());
           
        }catch(Exception e){
            e.printStackTrace();
            logger.error("bindSina is error "+e,e);
           
        }
        return "redirect:"+authorizationUrl;
    }
    @RequestMapping(value = "/forwardQQweibo2")
    public String forwardQQweibo2(QueryForm queryForm, String code,String openid,String openkey,
            ModelMap modelMap, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try{
               TuanDistributedHttpSession session = new TuanDistributedHttpSession(request, response);
               OAuthV2 oAuth = (OAuthV2)session.getAttribute("oAuth");
               qqWeiBo2.getAccessToken(oAuth,code, openid, openkey);
              
               qqWeiBo2.pulishMsg(oAuth,"封装完毕:Oauth2授权后发表一条带网络图片的微博", "http://ww1.sinaimg.cn/bmiddle/7e14fe22jw1dvbdwfyvpoj.jpg");
              
               qqWeiBo2.createFriend(oAuth,"linariel");
             
               MyUser user = qqWeiBo2.getUserInfo(oAuth, null);
              
               System.out.println(user.getId());
             
              
        }catch(Exception e){
            logger.error("异常信息:"+e,e);
            return "error";
        }
        return "error";
    }

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics