前端时间接触了一下人人网的开源API系统。分享一下自己的经验。
首先就是进入人人网开放平台官网 http://dev.renren.com/ 创建自己的一个站内用用
具体的创建流程在此就不多做解释。 附上官网教程的地址:
http://wiki.dev.renren.com/wiki/WEB%E7%AB%99%E5%86%85%E5%BA%94%E7%94%A8%E5%BC%80%E5%8F%91%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B
首先需要下载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;
}
}
男女比例的数据采集就这样简单的完成了,后续工作就是对页面进行美化。
原版的画面:
自己实现的画面
分享到:
相关推荐
CRAP - 开源API接口管理平台 | 完全开源、免费使用的API接口管理系统,BUG管理系统:API接口管理、文档管理、数据库表管理、接口调试、浏览器调试插件、导出word&pdf接口…..,采用SpringMVC + MyBatis + Lucene + ...
WebBuilder是一款跨平台、数据库和浏览器的可视化Web应用开发平台。WebBuilder使用了多项最新的技术,使Web应用的开发更快捷和简单。 作为一款高效的Web开发工具,WebBuilder的特色是: .基于浏览器的集成开发环境 ...
基于开源软件GIS应用平台开发,有一些启发和应用价值。
APIMAN 提供 API 管理的方法技术,结合一个 API 设计/配置层以及快速的运行时。主要特性:完全异步丰富的管理层容易嵌入API 管理 标签:APIMAN
PHP开源api管理平台源码v1.2 带后台.rar
开源代码使用指南 开源代码(Open Source):是促进软件发展的一种协作方式。与商用软件不同,它公开源代码, 允许用户直接拿来学习、开发。使用Open Source的应用受到Open Source的许可证限制,如有些 Open ...
提供应用全生命周期DevOps解决方案,全场景微服务、AppCube零代码开发能力,打通研发态、运行态、运维态,使能企业多种应用简单、敏捷开发上线。 提供一系列开箱即用的应用使能服务,帮助客户和伙伴高效构建精品应用...
开源的代码sqlapi,进行数据库移植时可能用到~~
智云全能API接口源码 接口源代码全开源智云全能API接口源码 接口源代码全开源智云全能API接口源码 接口源代码全开源智云全能API接口源码 接口源代码全开源智云全能API接口源码 接口源代码全开源智云全能API接口源码 ...
PHP开源api管理平台源码v1.2 带后台 可以做一个api聚合站 内附安装说明
开源框架人人,springboot + vue,亲测可用,这个是详细开发文档,有需要的朋友可以自行下载
Tyk还将记录有关您如何使用Tyk API Gateway的详细分析信息Tyk是一种轻量级的开源API网关,管理平台使您可以控制谁访问API,何时访问API以及访问方式。 Tyk还将记录有关您的用户如何与您的API交互以及何时出错的详细...
vue-cli实现论坛功能,根据cnode开源api开发,下载后直接使用npm install安装,npm run dev启动
本书系统介绍了微软新一代高效、跨平台的应用平台.NET Core 1.0。借助.NET Core,原本只能运行在Windows 上的.NET 应用可以运行在Linux、OS X...使用Cordova开发跨平台移动应用,使用Xamarin开发跨平台移动应用等内容。
ATC 是一个快速开发GO应用程序的开源框架,支持RESTful API 及 Thrift RPC的框架.可根据自身业务逻辑选择性的卸载中间件的功能,均支持平滑退出。
不断扩展的云网络边界和开源技术在其中的应用 网络操作系统-从开源到商用之路 白盒交换机探索 木兰社区开源项目实践 eBay网络云原生实践 基于开源的智能通信时代的思考 基于AI预测信息的边边协同计算机制研究初探 云...
ApiManager - CrapApi免费开源API接口管理系统、API接口调试工具:API接口管理、文档管理、接口调试
鉴于免费版访问量过大对于服务器压力过大现将免费版开源供大家离线调用.仅含2019年数据
Monk.Node 是一个免费开源的,快速、简单的面向对象的轻量级Node.JS开发框架,是为了敏捷WEB应用开发和简化企业应用开发而诞生的。Monk.Node从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的...
WebBuilder是一款跨平台、数据库和浏览器的可视化Web应用开发平台。WebBuilder使用了多项最新的技术,使Web应用的开发更快捷和简单。 作为一款高效的Web开发工具,WebBuilder的特色是: .基于浏览器的集成开发环境 ...