当前位置: 代码迷 >> Android >> android客户端联接人人网之二-获取签名
  详细解决方案

android客户端联接人人网之二-获取签名

热度:77   发布时间:2016-05-01 13:41:41.0
android客户端连接人人网之二----获取签名
官方文档:
http://dev.xiaonei.com/wiki/Calculate_signature

很简单
首先组装参数:
我们以friends.getFriends接口为例子:
required的参数是必选的,除了sig以外,因为签名值还没算,alternative的参数,要么选access_token,要么选api_key和session_key。Optional的参数是可选的,一般我们都要选上format这个参数,使返回的数据格式为JSON,这样解析的时候会方便很多,其它参数都是可选的
代码:
	private void getParams() {		String method = " friends.getFriends "; // 人人API中定义的方法,用于得到当前登录用户的好友列表。		int count = 30; // 得到用户数30个		List<String> param = new ArrayList<String>();		param.add("method=" + method);		param.add("v=1.0"); // 版本固定参数		param.add("access_token=" + RenrenUtil.access_token); // RenrenUtil.access_token																// 是在LoginActivity中已经保存的数据		param.add("format=JSON"); // 返回JSON数据		param.add("count=" + count); // 得到用户数		String signature = getSignature(param,				"换成自己的secret key"); // 第二个参数为 Secret Key		List<BasicNameValuePair> paramList = new ArrayList<BasicNameValuePair>();		paramList.add(new BasicNameValuePair("sig", signature)); // 签名		paramList.add(new BasicNameValuePair("method", method));		paramList.add(new BasicNameValuePair("v", "1.0"));		paramList.add(new BasicNameValuePair("access_token",				RenrenUtil.access_token));		paramList.add(new BasicNameValuePair("format", "JSON"));		paramList.add(new BasicNameValuePair("count", "" + count));	}

然后获取md5签名:
/**	 * 得到MD5签名	 * 	 * @param paramList	 * @param secret	 * @return	 */	public String getSignature(List<String> paramList, String secret) {		Collections.sort(paramList);		StringBuffer buffer = new StringBuffer();		for (String param : paramList) {			buffer.append(param); // 将参数键值对,以字典序升序排列后,拼接在一起		}		buffer.append(secret); // 符串末尾追加上应用的Secret Key		try {// 下面是将拼好的字符串转成MD5值,然后返回			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) {		}		return null;	}
  相关解决方案