腾讯微博授权登陆超简单示例(源自官方Demo)

来源:互联网 发布:网络电视经常卡怎么办 编辑:程序博客网 时间:2024/05/12 12:19
本人初学乍练 有什么不合适的地方欢迎大家踊跃吐槽 

首先参考官方API文档 了解腾讯微博Oauth2.0形式的授权过程 
这次主要将的是(code模式)方式的鉴权 
http://wiki.open.t.qq.com/index.php/API%E6%96%87%E6%A1%A3 

了解大致过程后 下载官方SDK 
我使用的是Java SDK 
http://wiki.open.t.qq.com/index.php/SDK%E4%B8%8B%E8%BD%BD#Java_SDK 

将官方SDK添加到项目中 
在项目名上右击 Build Path->Add External Archives...选择要添加的jar文件 


首先生成鉴权URL 
Java代码  收藏代码
  1. /** 
  2.  * 生成腾讯微博授权URL 
  3.  * @param request 
  4.  * @param m 
  5.  * @return 
  6.  * @throws IOException 
  7.  */  
  8. @RequestMapping(value = "/tencent/loginV2", method = RequestMethod.GET)  
  9. public String tencentLogin(HttpServletRequest request, Model m) throws IOException {  
  10.       
  11.                 String url = "http://open.t.qq.com/cgi-bin/oauth2/authorize?client_id=你申请的App Key&redirect_uri=回调地址&response_type=code";//  
  12.                 return "redirect:" + url;  
  13.   
  14.   
  15. }  


上一步生成了授权URL 会自动引导你到填写微博账户的登录页面 填写完成 验证通过后 会回调到你刚才提交的redirect_uri地址 

Java代码  收藏代码
  1.     /** 
  2.      * 腾讯微博登录成功后的回调地址 
  3.      * @param code 用来换取accesstoken的授权码,有效期为10分钟 
  4.      * @param openid 用户统一标识,可以唯一标识一个用户 
  5.      * @param openkey 与openid对应的用户key,是验证openid身份的验证密钥 
  6.      * @param oAuthV2 
  7.      * @param request 
  8.      * @param response 
  9.      * @param model 
  10.      * @return 
  11.      * @throws Exception 
  12.      */  
  13.     @RequestMapping(value = "/tencent/loginV2/callback", method = RequestMethod.GET)  
  14.     public String tencentLoginCallback(String code, String openid, String openkey,  
  15.             OAuthV2 oAuthV2,//2.0  
  16.             HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {  
  17.           
  18.          //设置授权 直接将授权码的参数记录到OAuth类中  
  19.          if ((!QStrOperate.hasValue(code)) ||  
  20.                 (!QStrOperate.hasValue(openid)) ||  
  21.                 (!QStrOperate.hasValue(openkey))) {  
  22.              return EnumErrorCode.ERROR_404.getValue();  
  23.          }  
  24.          oAuthV2.setAuthorizeCode(code);  
  25.          oAuthV2.setOpenid(openid);  
  26.          oAuthV2.setOpenkey(openkey);  
  27.            
  28.          oAuthV2.setClientId("申请时得到的AppKey");  
  29.          oAuthV2.setClientSecret("申请时得到的AppSecret");//大家可自行到腾讯微博开放平台申请  
  30.          oAuthV2.setRedirectUri("http://localhost/tencent/loginV2/callback");  
  31.          oAuthV2.setGrantType("authorization_code");  
  32.            
  33.          //检查是否取得code  
  34.          if(!QStrOperate.hasValue(oAuthV2.getAuthorizeCode())){  
  35.              oAuthV2.setStatus(2);  
  36.              return EnumErrorCode.ERROR_404.getValue();  
  37.          }else  
  38.              oAuthV2.setStatus(0);//没有出错  
  39.           
  40.         //访问Token  
  41.         String url = "https://open.t.qq.com/cgi-bin/oauth2/access_token";  
  42.         String queryString = QStrOperate.getQueryString(oAuthV2.getAccessTokenByCodeParamsList());  
  43.           
  44.         //请求accesstoken   
  45.         String responseData = Q_HTTP_CLIENT.httpGet(url, queryString);  
  46.           
  47.         //将服务器返回的包含access token等的回应包  解析存储到OAuth类中  
  48.         if (!parseAccessToken(responseData, oAuthV2)) {// Access Token 授权不通过  
  49.             oAuthV2.setStatus(3);  
  50.             return EnumErrorCode.ERROR_404.getValue();  
  51.         }  
  52.         //回调时可debug查看是否获得access token 下面为常用调用API测试方法  
  53.         //      String response1;  
  54. //        String format="json";  
  55. //        String clientip="127.0.0.1";  
  56. //        String jing ="";  
  57. //        String wei ="";  
  58. //        String syncflag="";  
  59. //        String content="2";// 注意:因为后台会对微博内容进行判重,所以在重复测试时加上变换部分++++++++  
  60. //        String reid=null;  
  61. //      String ids=null;  
  62. //      String id=null;  
  63. //        String picpath=System.getProperty("user.dir")+"\\src\\main\\resources\\logo_QWeibo.jpg";  
  64. //          
  65. //        TAPI tAPI=new TAPI(oAuthV2.getOauthVersion());//根据oAuth配置对应的连接管理器  
  66. //        //取得返回结果  
  67. //        response1=tAPI.add(oAuthV2, format, "测试发表文字微博"+content, clientip, jing, wei, syncflag);  
  68. //             // json数据使用  
  69. //             // response的结果可能是这样,{"data":{"id":"90221131024999","time":1333002978},"errcode":0,"msg":"ok","ret":0}  
  70. //             // 下面的代码将取出 id 的对应值,并赋予 reid  
  71. //            System.out.println("response = "+response1);  
  72. //            JSONObject responseJsonObject;  
  73. //            JSONObject dataJsonObject;  
  74. //            responseJsonObject= JSONObject.fromObject(response1);  
  75. //            dataJsonObject=(JSONObject)responseJsonObject.get("data");  
  76. //            id=ids=reid=dataJsonObject.get("id").toString();//对后面用到的 reid 赋值  
  77. //            System.out.println("reid = "+ reid);  
  78. //        try { Thread.sleep ( 5000 ) ; } catch (InterruptedException ie){}  
  79. //          
  80. //        tAPI.addPic(oAuthV2, format, "发表一条带本地图片的微博"+content, clientip, jing, wei, picpath, syncflag);  
  81. //        try { Thread.sleep ( 5000 ) ; } catch (InterruptedException ie){}  
  82. //          
  83. //        tAPI.addVideo(oAuthV2, format, "发表视频微博"+content, clientip, jing, wei, "http://www.tudou.com/programs/view/yx41TA6rQfE/?resourceId=0_03_05_07", syncflag);  
  84. //        try { Thread.sleep ( 5000 ) ; } catch (InterruptedException ie){}  
  85.   
  86.   
  87.         return "redirect:/";  
  88.     }  
  89.   
  90.     /** 
  91.      * 得到服务器返回的包含access token等的回应包后,解析存储到OAuth类中 
  92.      *  
  93.      * @param responseData 格式:access_token=ACCESS_TOKEN&expires_in=60&name=NAME 
  94.      * @param oAuth 
  95.      * @return 
  96.      */  
  97.      public  static boolean parseAccessToken(String responseData, OAuthV2 oAuth){  
  98.         if (!QStrOperate.hasValue(responseData)) {  
  99.             return false;  
  100.         }  
  101.   
  102.         oAuth.setMsg(responseData);  
  103.         String[] tokenArray = responseData.split("&");  
  104.           
  105.         if (tokenArray.length < 2) {  
  106.             return false;  
  107.         }  
  108.           
  109.         String tmpStr;  
  110.         for(int i=0;i<tokenArray.length;i++){  
  111.             if (tokenArray[i].startsWith("access_token=")){  
  112.                 tmpStr=tokenArray[i].substring(tokenArray[i].indexOf('=')+1, tokenArray[i].length());  
  113.                 if(!QStrOperate.hasValue(tmpStr)){  
  114.                     return false;  
  115.                 }  
  116.                 oAuth.setAccessToken(tmpStr);  
  117.             }  
  118.             if (tokenArray[i].startsWith("expires_in=")){  
  119.                 tmpStr=tokenArray[i].substring(tokenArray[i].indexOf('=')+1, tokenArray[i].length());  
  120.                 if(!QStrOperate.hasValue(tmpStr)){  
  121.                     return false;  
  122.                 }  
  123.                 oAuth.setExpiresIn(tmpStr);  
  124.             }  
  125.         }  
  126.           
  127.         return true;  
  128.     }  


如果成功发送了微博 说明授权成功 

写的比较仓促 鉴于本人也是初次接触 如果有什么不妥的地方欢迎大家吐槽 
0 0