新的起點 新的開始

          快樂生活 !

          實現(xiàn)從MSN Yahoo和Google導出用戶聯(lián)系人信息系列(4)—從Yahoo導出用戶聯(lián)系人(Step by Step) Setp 2 簡單實現(xiàn)

               接上節(jié),在上節(jié)中,我們申請了自己的域名,并且在Yahoo Developer上將該域名注冊得到了Oauth中的Consumer Key和Consumer secret,在這節(jié)里,我們將實現(xiàn)從Yahoo導出用戶聯(lián)系人信息。
               首先準備本地的環(huán)境,1. 安裝最新的Tomcat 當然其他的Servlert容器都可以 http 端口改為80。2 修改本地的C:\Windows\System32\drivers\etc\hosts 文件, 添加 127.0.0.1      advincenting.appspot.com(修改成你申請的域名)。
               第一步:調用 Yahoo的 get_request_token 代碼如下:
              
           1     String key = "dj0yJmk9QTVZcVN4QmVFYUlRJmQ9WVdrOU5uVnpZa3BxTXpZbWNHbzlOakEyTURRek1Ua3gmcz1jb25zdW1lcnNlY3JldCZ4PTQ3";// 這里是你注冊Yahoo 返回的consumer Key
           2     String secret = "2e8ac43ec5a506162a13acda0536d031cf94a9b4";";// 這里是你注冊Yahoo 返回的consumer secret
           4     String callback = "http://advincenting.appspot.com/delauth/threelegged/yahoo.jsp";
           5     String loginUrl ="";
           6     String guid ="";
           7     Map get_request_token = null;
           8     String oauth_token_secret =(String)session.getAttribute(TOKENSECRET);
           9     String oauthToken  =(String)session.getAttribute(TOKEN);
          10     session.removeAttribute(TOKENSECRET) ;
          11     session.removeAttribute(TOKEN) ;
          12    System.out.println("@@@@@@@@@@@@@@@@@@@@@@@"+oauthToken);
          13    String oauth_verifier = (String) request.getParameter("oauth_verifier");
          14    String oauth_token_request = (String) request.getParameter("oauth_token");
          15    String oauth_token4Setup4 ="";
          16    String oauth_token_secret_4Setup4 ="";
          17   ArrayList email = new ArrayList();
          18     if(oauthToken==null||oauthToken.equals("")){
          19          get_request_token = new HashMap();
          20        String reqUrl = 
          21            "https://api.login.yahoo.com/oauth/v2/" + "get_request_token?" + 
          22            "oauth_nonce=" + new Random().nextInt() + "&oauth_timestamp=" + 
          23            ((int)(System.currentTimeMillis() / 1000)) + 
          24            "&oauth_consumer_key=" + key + 
          25            "&oauth_signature_method=plaintext" + "&oauth_signature=" + 
          26            secret + "%26"  + "&oauth_version=1.0"+
          27        "&oauth_callback=http://advincenting.appspot.com/delauth/threelegged/yahoo.jsp"
          28            ;
          29
          30        System.out.println("##############################                          setup1:     "+reqUrl);
          31        HttpClient client = new HttpClient();
          32        GetMethod getm = new GetMethod(reqUrl);
          33        String returnStr ="";
          34
          35        try {
          36            client.executeMethod(getm);
          37            returnStr= getm.getResponseBodyAsString();
          38        }
           catch (HttpException e) {
          39            // TODO
          40        }
           catch (IOException e) {
          41            // TODO
          42        }

          43        
          44        String resp = returnStr;
          45        StringTokenizer st = new StringTokenizer(resp, "&");
          46        while (st.hasMoreTokens()) {
          47            String token = st.nextToken();
          48            get_request_token.put(token.substring(0, token.indexOf("=")), 
          49                                  token.substring(token.indexOf("="+ 1
          50                                                  token.length()));
          51        }

          52        System.out.println("Map got : " + get_request_token);
          53              loginUrl =
          54           URLDecoder.decode((String)get_request_token.get("xoauth_request_auth_url")) + 
          55           "&oauth_callback=" + callback;
          56
          57          String oauthTokenTemp =  (String) get_request_token.get("oauth_token");
          58          String oauth_token_secretTemp=  (String) get_request_token.get("oauth_token_secret");
          59        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%setup2:           "+loginUrl);
          通過第一步的調用我們就得到了 loginURL。然后我們可以讓用戶點擊該Link 跳轉到Yahoo登陸頁面   <a href="<%= loginUrl %>">Sign in</a>
           第二步:當用戶登陸成功后,由于我們配置了CallBack URL 所有Yahoo會跳轉到該JSP, 跳轉回來 我們在調用 getToken API 獲得Token 后就可以調用 getContact了
           
           1    if(oauthToken!=null&&!oauthToken.equals("")){
           2       Map accessMap = new HashMap();
           3       String accUrl = "https://api.login.yahoo.com/oauth/v2/get_token?"
           4        + "&oauth_consumer_key=" + key
           5        + "&oauth_signature_method=plaintext" + "&oauth_signature="
           6        +secret + "%26"  +oauth_token_secret  + "&oauth_version=1.0" + "&oauth_nonce="
           7        + new Random().nextInt() + "&oauth_timestamp="
           8        + ((int) (System.currentTimeMillis() / 1000)) + "&oauth_token="
           9        + oauthToken+"&oauth_verifier="
          10        + oauth_verifier;
          11        //System.out.println("oauth_verifier"+oauth_verifier);
          12        HttpClient client = new HttpClient();
          13        GetMethod getm = new GetMethod(accUrl);
          14         System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%setup3:           "+accUrl);
          15        try {
          16            client.executeMethod(getm);
          17            byte[] responseBody = getm.getResponseBody();
          18              System.out.println(new String(responseBody));
          19          returnStr2 =  URLDecoder.decode(new String(responseBody));
          20            //returnStr2= getm.getResponseBodyAsString();
          21        }
           catch (HttpException e) {
          22            // TODO
          23        }
           catch (IOException e) {
          24            // TODO
          25        }

          26        
          27        String resp =returnStr2;
          28        //System.out.println(resp);
          29        StringTokenizer st = new StringTokenizer(resp, "&");
          30        while (st.hasMoreTokens()) {
          31            String token = st.nextToken();
          32            accessMap.put((String)token.substring(0, token.indexOf("=")), (String)token.substring(token.indexOf("="+ 1, token.length()));
          33        }

          34        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"+accessMap);
          35         guid = (String)accessMap.get("xoauth_yahoo_guid");
          36       // System.out.println("guid"+guid);
          37            oauth_token4Setup4 =(String)accessMap.get("oauth_token");
          38        oauth_token_secret_4Setup4 =(String)accessMap.get("oauth_token_secret");
               第三步, 從上步,我們的到了 Token 和guid, 就可以調用getConttact API了


           1    if(guid!=null&&!guid.equals("")){
           2
           3        //String guidGetContact = "F2YX2QFU7D46NA6IWQBKT5DVMA";  //TODO replace to the real guid
           4          String resourceURL = "http://social.yahooapis.com/v1/user/"+ guid+"/contacts";
           5          List<Map.Entry<String, String>> parameters2 = new ArrayList<Map.Entry<String, String>>();
           6                parameters2.add(new OAuth.Parameter(
           7                      OAuth.OAUTH_SIGNATURE_METHOD,"HMAC-SHA1"));
           8                OAuthClient client = new OAuthClient(new HttpClient4());    
           9                OAuthConsumer consumer = new OAuthConsumer(
          10                  null,
          11               key,
          12               // consumer key
          13               secret, // consumer secret
          14               new OAuthServiceProvider(
          15               //
          16               "https://api.login.yahoo.com/oauth/v2/get_request_token"//
          17               "https://api.login.yahoo.com/oauth/v2/request_auth"//
          18               "https://api.login.yahoo.com/oauth/v2/get_token"));
          19                OAuthAccessor  accessor = new OAuthAccessor(consumer);
          20                accessor.accessToken = oauth_token4Setup4;
          21                accessor.tokenSecret = oauth_token_secret_4Setup4;
          22                String httpMethod = OAuthMessage.GET;
          23                OAuthMessage os =  client.invoke(accessor, httpMethod , resourceURL, parameters2);
          24                System.out.println("os==========" + os);
          25                System.out.println("os==========" + os.URL);
          26                HttpClient client4Invoke = new HttpClient();
          27                GetMethod getm = new GetMethod(os.URL);
          28        try {
          29            client4Invoke.executeMethod(getm);
          30            byte[] responseBody = getm.getResponseBody();
          31            
          32            File outFile = new File("d:\\testYahoo.xml");
          33            FileOutputStream fops = new FileOutputStream(outFile); 
          34            fops.write(responseBody); 
          35            fops.close();
          36
          37          returnStrContact =  URLDecoder.decode(new String(responseBody));
          38            //returnStr2= getm.getResponseBodyAsString();
          39            System.out.println(returnStrContact);
          40        }
           catch (HttpException e) {
          41            // TODO
          42        }
           catch (IOException e) {
          43            // TODO
          44        }
          finally{
          45        
          46        }

          47        
                第四步,解析返回的XML格式的Contact

           

           1            
           2           SAXReader saxReader = new SAXReader();
           3
           4            Document document = null;
           5                document = saxReader.read(new File("d:\\testYahoo.xml"));
           6            Element root = document.getRootElement();
           7            int num = -1;
           8            for (Iterator iter = root.elementIterator(); iter.hasNext(); ) {
           9                Element element = (Element)iter.next();
          10                num++;
          11                System.out.println(element.elements("fields").size());
          12                List contactList = element.elements("fields");
          13                for(int i =0; i<contactList.size();i++){
          14
          15                  Element elementTemp = (Element)contactList.get(i);
          16                       if( elementTemp.element("type").getTextTrim().equals("email")){
          17                           System.out.println(elementTemp.element("value").getTextTrim());
          18                           email.add(elementTemp.element("value").getTextTrim());
          19                       }
          ;
          20                       
          21
          22           
          23
          24                    }

          25                
          26                }

          27      System.out.println(email.size());        
          28

          結果如下:
          Setup 1:調用get_request_token  得到 loginURL 用戶點擊登陸

          2. 登陸


          3. 授權訪問

          4. CallBack到我們的JSP 然后調用getToken 得到Token和guid, 繼續(xù)調用getContact API 獲得Email等相關信息



               從Yahoo導出用戶聯(lián)系簡單的例子就完成了,后續(xù)章節(jié)里我們將繼續(xù)討論MSN Google的實現(xiàn)。在最后我們將重新設計集成從這三個站點導出聯(lián)系人的實現(xiàn)。 完整例子下載  
               下載完整的例子到你本地,僅僅修改你本地host的文件就Ok了。



          posted on 2010-01-07 22:55 advincenting 閱讀(3292) 評論(3)  編輯  收藏

          評論

          # re: 實現(xiàn)從MSN Yahoo和Google導出用戶聯(lián)系人信息系列(4)—從Yahoo導出用戶聯(lián)系人(Step by Step) Setp 2 簡單實現(xiàn) 2010-01-08 12:32 樂蜂網(wǎng)精油

          速度飛快的是開發(fā)  回復  更多評論   

          # re: 實現(xiàn)從MSN Yahoo和Google導出用戶聯(lián)系人信息系列(4)—從Yahoo導出用戶聯(lián)系人(Step by Step) Setp 2 簡單實現(xiàn) 2010-01-13 17:47 oyxz

          google支持,但是msn好象暫時還不支持oauth驗證功能.  回復  更多評論   

          # re: 實現(xiàn)從MSN Yahoo和Google導出用戶聯(lián)系人信息系列(4)—從Yahoo導出用戶聯(lián)系人(Step by Step) Setp 2 簡單實現(xiàn) 2013-01-08 23:10 nooneyanghui

          OAuthMessage os = client.invoke(accessor, httpMethod , resourceURL, parameters2);這里的資源怎么釋放掉,我看了這個方法的源代碼沒有釋放資源的方法,求指教  回復  更多評論   


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           

          公告

          Locations of visitors to this pageBlogJava
        1. 首頁
        2. 新隨筆
        3. 聯(lián)系
        4. 聚合
        5. 管理
        6. <2010年1月>
          272829303112
          3456789
          10111213141516
          17181920212223
          24252627282930
          31123456

          統(tǒng)計

          常用鏈接

          留言簿(13)

          隨筆分類(71)

          隨筆檔案(179)

          文章檔案(13)

          新聞分類

          IT人的英語學習網(wǎng)站

          JAVA站點

          優(yōu)秀個人博客鏈接

          官網(wǎng)學習站點

          生活工作站點

          最新隨筆

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 沅陵县| 玛沁县| 图们市| 金乡县| 米泉市| 太仆寺旗| 乐业县| 惠来县| 连州市| 祁阳县| 衡阳市| 武宁县| 丽水市| 高雄市| 龙门县| SHOW| 梁平县| 木里| 鹰潭市| 綦江县| 秦皇岛市| 沾化县| 凤山市| 长治市| 新野县| 宁强县| 集贤县| 江阴市| 光山县| 中牟县| 汨罗市| 林州市| 丰都县| 襄城县| 垦利县| 镶黄旗| 藁城市| 龙川县| 永定县| 兴和县| 镇远县|