接上节,在上节中,我们申请了自己的域名,并且在Yahoo Developer上将该域名注册得到了Oauth中的Consumer Key和Consumer secret,在这节里,我们将实现从Yahoo导出用户联系人信息。
首先准备本地的环境,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, 继续调用getContact API 获得Email等相关信息
从Yahoo导出用户联系简单的例子就完成了,后续章节里我们将继续讨论MSN Google的实现。在最后我们将重新设计集成从这三个站点导出联系人的实现。 完整例子下载
下载完整的例子到你本地,仅仅修改你本地host的文件就Ok了。