使用人人网开源API的站内应用开发
前端时间接触了一下人人网的开源API系统。分享一下自己的经验。
首先就是进入人人网开放平台官网 http://dev.renren.com/ 创建自己的一个站内用用
具体的创建流程在此就不多做解释。 附上官网教程的地址:
首先需要下载SDK包,请下载java-sdk 和 javascript-sdk
下载地址:http://wiki.dev.renren.com/wiki/SDK
略去一些其他步骤,直接进入代码阶段。准备好创建应用留下的三个数据:应用ID、API KEY、Secret Key
接下来以实现人人网的一个热门应用--好友档案的男女比例的例子来介绍如何使用人人网的开放API
第一步就是用户进行授权,所有的应用都需要用户进行授权,在Javascript-sdk中已经实现了,只要去调用就好了。官网上也有例子。
先建立一个工具类来存放应用ID、API KEY、Secret Key
public final class AppConfig {
public static final String APP_ID = "123456"; //你自己的应用ID
public static final String API_KEY = "4897d1193b3445839fe2ab0*********"; //API KEY
public static final String APP_SECRET = "7c95d8871f6d451eba11f05*********"; //Secret Key
}
接着再创建一个Servlet
package com.mytest.webcanvas;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mytest.webcanvas.config.AppConfig;
@SuppressWarnings("serial")
public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
request.setAttribute("appId", AppConfig.APP_ID);
RequestDispatcher welcomeDispatcher = request.getRequestDispatcher("/views/welcome.jsp");
welcomeDispatcher.forward(request, response);
}
}
再在相应的目录下面创建welcome.jsp文件
<%@ page contentType="text/html;charset=UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title> Welcome</title> <script type="text/javascript" src="./js/renren.js"></script> </head> <body> <script type="text/javascript"> var uiOpts = { url : "http://graph.renren.com/oauth/authorize", display : "iframe", params : {"response_type":"token","client_id":"${requestScope.appId}"}, onSuccess: function(r){ top.location = "http://apps.renren.com/heylink/main"; }, onFailure: function(r){} }; Renren.ui(uiOpts); </script> Hi, Welcome!!! </body> </html>
上述程序中的JS代码,会弹出的授权显示,注意的是"client_id" 这个地方 后面要填上你自己的APPID
注意这里的onSuccess方法,在成功授权之后,会跳到相应的页面去,也就是说,在授权成功后就开始进入该应用。
以上的代码 ,在人人网的官网上也都有。
调用人人网API
这里采用的是向目标URL地址以POST方式发送Http请求,明确指定调用那个方法,然后以XML格式或者JSON格式返回请求。
一下代码实现好友档案中的“男女比例”
package com.mytest.business;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import com.mytest.bean.SexRatio;
import com.mytest.webcanvas.config.AppConfig;
import com.renren.api.client.RenrenApiClient;
import com.util.Renren;
import com.util.Signature;
import com.util.HttpHelper;
public class SexRatioDAO {
//参数sessionKey是调用API不可少的
//参数renrenUserId代表授权的用户,用自己帐号在测试的时候,这个参数就代表你自己人人网的Id
/* 在授权后的Servlet中可以用下面这种方式取得,然后保存到Session中,以后需要用的时候
* 就可以从Session里去取
*
*
String sessionKey = request.getParameter("xn_sig_session_key");
String renrenUserId = request.getParameter("xn_sig_user");
*/
public SexRatio getSexRatio(String sessionKey, String renrenUserId) {
RenrenApiClient apiClient = new RenrenApiClient(sessionKey);
//这是一个JavaBean,在后面会附上代码
SexRatio sexRatio = new SexRatio();
if (sessionKey != null) {
// 用户Id,这里表示你自己的
Long uid = Long.parseLong(renrenUserId);
// 应用的Secret Key
String secret = AppConfig.APP_SECRET;
// 应用的API Key
String apiKey = AppConfig.API_KEY;
// 接口名称
// API文档的地址:http://wiki.dev.renren.com/wiki/Users.getProfileInfo
String requestMethod = "users.getProfileInfo";
// API的版本号,请设置成1.0,这个是必须的
String v = "1.0";
/* 请求接口所要求的参数,因接口不同而不同。这里的friends_count值返回好友的总个数,还可以返回更多
* 的数据,根据输入不同的参数、参数个数而返回不同的数据
* 在人人网API文档中对Users.getProfileInfo的fileds的描述
* 需要获取的信息的字段列表,各个字段用逗号隔开。目前支持以下字段:base_info(基本信息),
* status(当前状态),visitors_count(来访总数),blogs_count(日志总数),
* albums_count(相册总数),friends_count(好友总数),guestbook_count(留言的总数),
* status_count(状态的总数),各个字段用逗号隔开。其中base_info包括性别、生日、家乡、网络。
* 缺省或者用户有隐私设置时只返回用户ID,姓名,头像,是否为星级用户。
*/
String fields = "friends_count";
// 请求人人网开放平台API服务器的地址
String url = Renren.API_URI;
/*
*
* 为获取签名
“签名”就是在API文档中系统级参数中的必不可少的一项
在下面的signature就代表签名,使用Signature类的getSignature()计算后取得该值
*/
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("api_key", apiKey);
paramMap.put("method", requestMethod);
paramMap.put("uid", uid.toString());
paramMap.put("v", v);
paramMap.put("session_key", sessionKey);
paramMap.put("fields", fields);
//设置请求返回的类型,这里指定为JSON
paramMap.put("format", "JSON");
// 上述的签名
String signature = Signature.getSignature(paramMap, secret);
PostMethod method = new PostMethod(url);
// 将以上准备好的参数添加到method对象中
method.addParameter("api_key", apiKey);
method.addParameter("method", requestMethod);
method.addParameter("uid", uid.toString());
method.addParameter("v", v);
method.addParameter("session_key", sessionKey);
method.addParameter("fields", fields);
method.addParameter("sig", signature);
method.addParameter("format", "JSON");
//得到一个HttpClient实例,因为这个实例经常要被使用,所以采用单例模式返回这个实例
HttpClient client = HttpHelper.getHttpHelper();
try {
client.executeMethod(method);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 返回请求的结果
String str = method.getResponseBodyAsString(); //该请求返回的是一串字符串
//将字符串转换为一个JSONObject对象
JSONObject json = (JSONObject) JSONValue.parse(str);
//从JSONObject对象中取得值,也就是好友总个数的值
Long res = (Long) json.get("friends_count");
int count = res.intValue();
// 设置好友总数
sexRatio.setSum(count);
// 获取好友列表数据,将好友的总数放入getFriends方法以取得全部好友的资料
JSONArray friendsList = apiClient.getFriendsService().getFriends(1, count);
//遍历获取好友的性别
for (int i = 0; i < friendsList.size(); i++) {
JSONObject friends = (JSONObject) friendsList.get(i);
String sex = (String) friends.get("sex");
if (sex.equals("1")) { //如果是男生
sexRatio.setManNums(sexRatio.getManNums()+1);
} else if (sex.equals("0")) { //如果是女生
sexRatio.setWomenNums(sexRatio.getWomenNums()+1);
}
}
//获取授权用户自己的性别,如果自己是男生,那么异性就是女生,如果自己是女生则反之,这里可以调用Java-sdk中已封装的方法
JSONArray userInfo = apiClient.getUserService().getInfo(
renrenUserId, "sex");
JSONObject currentUser = (JSONObject)userInfo.get(0);
Long userSex = (Long) currentUser.get("sex");
String userSexString = userSex + "";
// ------------- 要取的数据取完,以下代码用来生成其他数据项 ------------
/*一下代码用来生成一些其他数据,例如异性好友占同性好友的比例,根据比例产生好色指数等··不做解释*/
double manRatio = 0.0;
int sum = sexRatio.getManNums()+ sexRatio.getWomenNums();
manRatio = sexRatio.getManNums() * 1.0 / sum;
String sub = manRatio+"";
sub = sub.substring(2, 4);
int indexNum = Integer.parseInt(sub);
int indexNum2 = 100 - indexNum;
sexRatio.setManRatio(indexNum + "");
sexRatio.setWomenRatio(indexNum2 + "");
NumberFormat nf = new DecimalFormat("0.0");
double biger = 0.0;
if(userSexString.equals("1")) {
biger = sexRatio.getWomenNums()*1.0 / sexRatio.getManNums();
}else if(userSexString.equals("0")){
biger = sexRatio.getManNums()*1.0 / sexRatio.getWomenNums();
}
sexRatio.setBiger(nf.format(biger));
if(biger - 0.5 < 0.000001) {
sexRatio.setDescription("绝世无双的好基友!");
sexRatio.setSexRatioCount("1");
}else if(biger - 0.8 < 0.000001) {
sexRatio.setDescription("还好还好一般性过的去比较正常");
sexRatio.setSexRatioCount("2");
}else if(biger - 1.0 < 0.000001) {
sexRatio.setDescription("绝对正常");
sexRatio.setSexRatioCount("3");
}else if(biger - 1.5 < 0.000001) {
sexRatio.setDescription("开始有点色了");
sexRatio.setSexRatioCount("4");
}else {
sexRatio.setDescription("非常重色!");
sexRatio.setSexRatioCount("5");
}
}
//返回bean
return sexRatio;
}
}
附上其他的工具类
HttpHelper 类
package com.util;
import org.apache.commons.httpclient.HttpClient;
public class HttpHelper {
private static HttpClient httpClient;
public static HttpClient getHttpHelper() {
if(httpClient == null) {
httpClient = new HttpClient();
}
return httpClient;
}
}
Renren类
package com.util;
public class Renren {
public static String API_URI = "http://api.renren.com/restserver.do";
}
Signature类(生成传说中的“签名”)
package com.util;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class Signature {
public static String getSignature(Map<String, String> paramMap, String secret) {
List<String> paramList = new ArrayList<String>(paramMap.size());
//1、参数格式化
for(Map.Entry<String,String> param:paramMap.entrySet()){
paramList.add(param.getKey()+"="+param.getValue());
}
//2、排序并拼接成一个字符串
Collections.sort(paramList);
StringBuffer buffer = new StringBuffer();
for (String param : paramList) {
buffer.append(param);
}
//3、追加script key
buffer.append(secret);
//4、将拼好的字符串转成MD5值
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
StringBuffer result = new StringBuffer();
try {
for (byte b : md.digest(buffer.toString().getBytes("UTF-8"))) {
result.append(Integer.toHexString((b & 0xf0) >>> 4));
result.append(Integer.toHexString(b & 0x0f));
}
} catch (UnsupportedEncodingException e) {
for (byte b : md.digest(buffer.toString().getBytes())) {
result.append(Integer.toHexString((b & 0xf0) >>> 4));
result.append(Integer.toHexString(b & 0x0f));
}
}
return result.toString();
} catch (java.security.NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return null;
}
}
SexRatio类
package com.mytest.bean;
public class SexRatio {
private String sexRatioCount; //重色轻友指数
private String description; //根据指数描述
private int Sum; //总人数
private int manNums; //男生好友数
private int womenNums; //女生好友数
private String manRatio; //男生好友比例
private String womenRatio; //女生好友比例
private String biger; //多余异性的倍数
public SexRatio() {
sexRatioCount="";
description="";
Sum=0;
manNums=0;
womenNums=0;
manRatio="";
womenRatio="";
biger="";
}
public int getSum() {
return Sum;
}
public void setSum(int sum) {
Sum = sum;
}
public String getSexRatioCount() {
return sexRatioCount;
}
public void setSexRatioCount(String sexRatioCount) {
this.sexRatioCount = sexRatioCount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getManNums() {
return manNums;
}
public void setManNums(int manNums) {
this.manNums = manNums;
}
public int getWomenNums() {
return womenNums;
}
public void setWomenNums(int womenNums) {
this.womenNums = womenNums;
}
public String getManRatio() {
return manRatio;
}
public void setManRatio(String manRatio) {
this.manRatio = manRatio;
}
public String getWomenRatio() {
return womenRatio;
}
public void setWomenRatio(String womenRatio) {
this.womenRatio = womenRatio;
}
public String getBiger() {
return biger;
}
public void setBiger(String biger) {
this.biger = biger;
}
}
男女比例的数据采集就这样简单的完成了,后续工作就是对页面进行美化。
原版的画面:
自己实现的画面