腾讯云java服务器端集成 账号关系 单聊消息 消息推送 关系链管理

jar包


TXCloudUtils.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class TXCloudUtils
{
	public static final String nickname = "Tag_Profile_IM_Nick";//昵称
	public static final String sex = "Tag_Profile_IM_Gender";//性别
	public static final String image = "Tag_Profile_IM_Image";//头像
	public static final String remark = "Tag_SNS_IM_Remark";//备注
	public static final String male = "Gender_Type_Male";//男
	public static final String female = "Gender_Type_Female";//女
	
	/**
	 * 账号绑定
	 * @param uid 用户uid
	 * @param nickname 用户昵称
	 * @param image 用户头像
	 * @return
	 */
	public static byte AccountImport(long uid,String nickname,String image)
	{
		Map<String, String> map = new HashMap<String, String>();
		map.put("Identifier", String.valueOf(uid));
		map.put("Nick", nickname);
		map.put("FaceUrl", image);
		String json = JSON.toJSONString(map);//拼装json数据
		JSONObject jObject = JSON.parseObject(TXCloudHelper.executePost(TXCloudHelper.getUrl(CloudData.accountImport), json));
		return jObject.get("ActionStatus").toString().equals("OK") ? (byte)1 : (byte)0;
	}
	
	/**
	 * @see 管理员向其他指定账户发送消息
	 * @param uid
	 * @param MsgType
	 * @param msg
	 * @return
	 */
	public static byte OpenimSendMsg(long uid,String msg)
	{
		Map<Object, Object> map= new HashMap<Object, Object>();//拼装json数据
		List<Object> list = new ArrayList<Object>();
		list.add(setMsgBody(msg));//消息体内容
		map.put("SyncOtherMachine", 1);//1:把消息同步到From_Account在线终端和漫游上;2:消息不同步至From_Account;若不填写默认情况下会将消息存From_Account漫游
		map.put("To_Account", String.valueOf(uid));//消息接收方账号。
		map.put("MsgLifeTime", 604800);//消息离线保存时长(秒数),最长为7天(604800s)。若消息只发在线用户,不想保存离线,则该字段填0。若不填,则默认保存7天
		map.put("MsgRandom", TXCloudHelper.randomInt(Integer.MAX_VALUE));//消息随机数,由随机函数产生。(用作消息去重)
		map.put("MsgTimeStamp", System.currentTimeMillis()/1000);//消息时间戳,unix时间戳。
		map.put("MsgBody", list);//设置消息体
		String json = JSON.toJSONString(map);
		JSONObject jObject = JSON.parseObject(TXCloudHelper.executePost(TXCloudHelper.getUrl(CloudData.openimSendmsg), json));
		return jObject.get("ActionStatus").toString().equals("OK") ? (byte)1 : (byte)0;	
	}
	
	/**
	 * @see 管理员发送推送
	 * @param MsgType
	 * @param msg
	 * @return
	 */
	public static byte ImPush(String msg)
	{	
		Map<Object, Object> map= new HashMap<Object, Object>();//拼装json数据
		List<Object> list = new ArrayList<Object>();
		list.add(setMsgBody(msg));
		map.put("MsgRandom", TXCloudHelper.randomInt(Integer.MAX_VALUE));
		map.put("MsgBody", list);
		String json = JSON.toJSONString(map);
		JSONObject jObject = JSON.parseObject(TXCloudHelper.executePost(TXCloudHelper.getUrl(CloudData.openimIm_push), json));
		return jObject.get("ActionStatus").toString().equals("OK") ? (byte)1 : (byte)0;	
	}
	
	/**
	 * @see 设置用户属性
	 * @param userInfo
	 * @return
	 */
	public static boolean setPortrait(Long uid,UserInfo userInfo)
	{
		List<Map<String, Object>> list = setProfileItem(userInfo);
		Map<Object, Object> map= new HashMap<Object, Object>();//拼装json数据
		map.put("From_Account", String.valueOf(uid));
		map.put("ProfileItem", list);
		String json = JSON.toJSONString(map);
		JSONObject jObject = JSON.parseObject(TXCloudHelper.executePost(TXCloudHelper.getUrl(CloudData.setPortrait), json));
		return jObject.get("ActionStatus").toString().equals("OK") ? true : false;	
	}
	
	/**
	 * @see 获取用户属性
	 * @param uid
	 * @return
	 */
	public static String getPortrait(Long uid)
	{
		List<String>list = new LinkedList<String>();
		list.add(nickname);
		list.add(image);
		list.add(sex);
		Map<Object, Object> map= new HashMap<Object, Object>();//拼装json数据
		map.put("TagList", list);
		List<String> accList = new LinkedList<String>();
		accList.add(String.valueOf(uid));
		map.put("To_Account", accList);
		String json = JSON.toJSONString(map);
		JSONObject jObject = JSON.parseObject(TXCloudHelper.executePost(TXCloudHelper.getUrl(CloudData.getPortrait), json));
		if(!jObject.get("ActionStatus").toString().equals("OK")) 
		{
			return null;
		}
		else 
		{
			return JSON.toJSONString(getUserInfo(jObject));	
		}
	}
	
	/** 增加好友,设置好友备注
	 * @param uid 用户uid
	 * @param fuid 好友uid
	 * @param addSource 加好友来源平台
	 * @return
	 */
	public static byte addFriend(long uid, long fuid, String Remark, String addSource)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		LinkedList<Map<String, String>> list = new LinkedList<>();
		Map<String, String> fmap = new HashMap<String, String>();
		fmap.put("To_Account", String.valueOf(fuid));//好友的Identifier。
		fmap.put("AddSource", "AddSource_Type_"+addSource);//加好友来源 如:AddSource_Type_Android
		if(!Remark.isEmpty())
		{
			fmap.put("Remark", Remark);	
		}
		list.add(fmap);
		map.put("From_Account", String.valueOf(uid));//需要为该Identifier添加好友。
		map.put("AddFriendItem", list);//好友结构体对象。
		
		String json = JSON.toJSONString(map);//拼装json数据
		JSONObject jObject = JSON.parseObject(TXCloudHelper.executePost(TXCloudHelper.getUrl(CloudData.addFriend), json));
		if(jObject.get("ActionStatus").toString().equals("OK")){
			String relation =  jObject.getJSONArray("ResultItem").getJSONObject(0).getString("ResultInfo");
			if(!relation.equals("SNS_FRD_ADD_FRD_EXIST"))//已经是好友
				return 1;
		}
		return 0;
	}
	
	/** 删除好友
	 * @param uid 用户uid
	 * @param fuid 好友uid
	 * @return
	 */
	public static byte deleteFriend(long uid, long fuid)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		LinkedList<String> list = new LinkedList<>();
		list.add(String.valueOf(fuid));
		map.put("From_Account", String.valueOf(uid));//需要为该Identifier删除好友。
		map.put("To_Account", list);//待删除的好友的Identifier。
		map.put("DeleteType", "Delete_Type_Both");//双向删除好友
		String json = JSON.toJSONString(map);//拼装json数据
		JSONObject jObject = JSON.parseObject(TXCloudHelper.executePost(TXCloudHelper.getUrl(CloudData.deleteFriend), json));
		return jObject.get("ActionStatus").toString().equals("OK") ? (byte)1 : (byte)0;
	}
	
	/** 检验好友
	 * @param uid 用户uid
	 * @param fuid 好友uid
	 * @return
	 */
	public static byte checkFriend(long uid, long fuid)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		LinkedList<String> list = new LinkedList<>();
		list.add(String.valueOf(fuid));
		map.put("From_Account", String.valueOf(uid));//需要为该Identifier校验好友。
		map.put("To_Account", list);//待校验的好友的Identifier。
		map.put("CheckType", "CheckResult_Type_Both");//双向校验好友关系
		String json = JSON.toJSONString(map);//拼装json数据
		JSONObject jObject = JSON.parseObject(TXCloudHelper.executePost(TXCloudHelper.getUrl(CloudData.checkFriend), json));
		if(jObject.get("ActionStatus").toString().equals("OK")){
			String relation =  jObject.getJSONArray("InfoItem").getJSONObject(0).getString("Relation");
			if(relation.equals("CheckResult_Type_BothWay"))
				return 1;
		}
		return 0;
	}
	
	/** 获取指定单个好友信息
	 * @param uid
	 * @param fuid
	 * @return
	 */
	public static String getOneFriend( long uid, long fuid)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("From_Account", String.valueOf(uid));//需要拉取该Identifier的好友。
		
		LinkedList<String> To_Account = new LinkedList<String>();
		To_Account.add(String.valueOf(fuid));
		map.put("To_Account", To_Account);//请求拉取的好友的Identifier列表
		
		LinkedList<String> flist = new LinkedList<String>();
		flist.add(nickname);//昵称
		flist.add(image);//头像URL
		flist.add(remark);//备注
		map.put("TagList", flist);//指定要拉取的资料字段及好友字段
		
		String json = JSON.toJSONString(map);//拼装json数据
		JSONObject jObject = JSON.parseObject(TXCloudHelper.executePost(TXCloudHelper.getUrl(CloudData.getFriend), json));
		
		String ResultInfo = jObject.getJSONArray("InfoItem").getJSONObject(0).getString("ResultInfo");
		
		if(ResultInfo.equals("SNS_FRD_GET_LIST_FRD_NO_EXIST"))//不是好友
		{
			return null;
		}
		else
		{
			FriendInfo friendInfo = new FriendInfo();
			friendInfo.setFuid(fuid);
			return JSON.toJSONString(getFriendInfo(friendInfo, jObject.getJSONArray("InfoItem").getJSONObject(0).getJSONArray("SnsProfileItem")));
		}
	}
	
	/** 获取所有好友列表
	 * @param uid 用户uid
	 * @param startIndex 拉取的起始位置
	 * @return
	 */
	public static String getAllFriend(long uid, int startIndex)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		LinkedList<String> list = new LinkedList<>();
		list.add(nickname);//昵称
		list.add(image);//头像URL
		list.add(remark);//好友备注
		map.put("TagList", list);//指定要拉取的字段Tag
		map.put("From_Account", String.valueOf(uid));//需要拉取该Identifier的好友。
		map.put("StartIndex", startIndex);//拉取的起始位置。
		map.put("GetCount", 50);//每页需要拉取的好友数量
		String json = JSON.toJSONString(map);//拼装json数据
		JSONObject jObject = JSON.parseObject(TXCloudHelper.executePost(TXCloudHelper.getUrl(CloudData.getAllFriend), json));
		
		List<FriendInfo> flist = new ArrayList<>();
		if(jObject.get("ActionStatus").toString().equals("OK")){
			JSONArray jsona = jObject.getJSONArray("InfoItem");
			if (jsona.size() > 0) {
				for (Object object : jsona) {
					JSONObject job = (JSONObject) object;
					FriendInfo friendInfo = new FriendInfo();
					friendInfo.setFuid(job.getLongValue("Info_Account")); //好友uid
					flist.add(getFriendInfo(friendInfo, job.getJSONArray("SnsProfileItem")));
				}
			}
		}
		
		return JSON.toJSONString(flist);
	}
	
	
	/**
	 * @see 设置消息体内容
	 * @param MsgType
	 * @param msg
	 * @return
	 */
	public static Map<String, Object> setMsgBody(String msg)
	{
		Map<String, Object> msgMap = new HashMap<String, Object>();
		msgMap.put("MsgType", "TIMTextElem");
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("Text", msg);
		msgMap.put("MsgContent", map);
		return msgMap;
	}
	
	/**
	 * @see 设置资料对象数组(设置用户属性)
	 * @param userInfo
	 * @return
	 */
	public static List<Map<String, Object>> setProfileItem(UserInfo userInfo)
	{
		List<Map<String, Object>> list = new LinkedList<Map<String,Object>>();
		if(!userInfo.getNickname().isEmpty()) 
		{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("Tag", nickname);
			map.put("Value", userInfo.getNickname());
			list.add(map);
		}
		if(null != userInfo.getSex()) 
		{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("Tag", sex);
			if (0 == userInfo.getSex()) {
				map.put("Value",female);
			}
			else if (1 == userInfo.getSex()) 
			{
				map.put("Value", male);
			}
			else {
				map.put("Value", "Gender_Type_Unknown");
			}
			list.add(map);
		}
		
		if(!userInfo.getImage().isEmpty()) 
		{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("Tag", image);
			map.put("Value", userInfo.getImage());
			list.add(map);
		}
		return list;
	}
	
	/**
	 * @see 获取用户信息
	 * @param json
	 * @return
	 */
	public static UserInfo getUserInfo(JSONObject json)
	{
		UserInfo userInfo = new UserInfo();
		JSONArray jsonArray =  json.getJSONArray("UserProfileItem").getJSONObject(0).getJSONArray("ProfileItem");
		for (Object obj : jsonArray) {
			JSONObject ob = (JSONObject)obj;
			if(nickname.equals(ob.getString("Tag"))) 
			{
				userInfo.setNickname(ob.getString("Value"));
			}
			else if(sex.equals(ob.getString("Tag"))) 
			{
				if(ob.getString("Value").equals("Gender_Type_Unknown")) 
				{
					userInfo.setSex((byte) -1);//性别位置
				}
				else if(ob.getString("Value").equals(female))
				{
					userInfo.setSex((byte) 0);//女
				}
				else 
				{
					userInfo.setSex((byte) 1);//男
				}
			}
			else if(image.equals(ob.getString("Tag"))) 
			{
				userInfo.setImage(ob.getString("Value"));
			}
		}
		return userInfo;
		
	}
	
	/** 获取好友信息
	 * @param friendInfo
	 * @param jsonar
	 * @return
	 */
	public static FriendInfo getFriendInfo(FriendInfo friendInfo, JSONArray jsonar){
		if (jsonar.size() > 0) {
			for (Object object : jsonar) {
				JSONObject jobo = (JSONObject) object;
				if(jobo.getString("Tag").equals(nickname)){
					friendInfo.setNickname(jobo.getString("Value"));//昵称
				}
				if(jobo.getString("Tag").equals(image)){
					friendInfo.setImage(jobo.getString("Value")); //头像url
				}
				if(jobo.getString("Tag").equals(remark)){
					friendInfo.setRemark(jobo.getString("Value")); //备注
				}
			}
		}
		return friendInfo;
	}
}

CloudData.java

public class CloudData 
{
	public static final String accountImport = "im_open_login_svc/account_import";//新建用户(独立模式账号导入接口)
	public static final String openimSendmsg = "openim/sendmsg";//管理员向账号发消息(单发单聊消息)
	public static final String openimIm_push = "openim/im_push";//消息推送
	public static final String getPortrait = "profile/portrait_get";//拉取用户资料
	public static final String setPortrait = "profile/portrait_set";//设置用户资料
	public static final String addFriend = "sns/friend_add";//增加好友
	public static final String deleteFriend = "sns/friend_delete";//删除好友
	public static final String checkFriend = "sns/friend_check";//检验好友
	public static final String getFriend = "sns/friend_get_list";//获取指定单个好友信息
	public static final String getAllFriend = "sns/friend_get_all";//获取所有好友列表
}


TXCloudHelper.java

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Random;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class TXCloudHelper 
{
	/**
	 * @see 获取url
	 * @param servicename
	 * @return
	 */
	public static String getUrl(String servicename)
	{
		String url = "https://console.tim.qq.com/v4/"+servicename+"?"+"usersig="+ CloudSignHelper.GetSign(identifier) +"&identifier=" + identifier + "&sdkappid=" + appid
				"&random=" + randomInt() +"&contenttype=json";
		return url;
	}
	
	/**
	 * @see 发送post请求
	 * @param url
	 * @param headers
	 * @return
	 */
	public static String executePost(String url, String parameters) 
	{	
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
		HttpPost method =  new HttpPost(url);  
		String body = null;  
	    if(method != null & parameters != null && !"".equals(parameters.trim())) 
	    {  
	        try{  
	            //建立一个NameValuePair数组,用于存储欲传送的参数  
	            method.addHeader("Content-type","application/json; charset=utf-8");  
	            method.setHeader("Accept", "application/json");  
	            method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));  	
	            HttpResponse response = closeableHttpClient.execute(method);  	              
	            int statusCode = response.getStatusLine().getStatusCode();  	              
	            if(statusCode != HttpStatus.SC_OK) 
	            {  
	            	System.out.println(response.getStatusLine());  
	            }  	
	            //获取响应数据
	            body = EntityUtils.toString(response.getEntity());  	
	        } catch (IOException e) {  
	        	e.printStackTrace();
	        }
	    }  
    return body;  
    }  
	
	/**
	 * @see 随机数
	 */
	public static int randomInt()
	{
		Random random = new Random();
		return random.nextInt();
	}
	
	/**
	 * @see 取值范围[0,upper)
	 */
	public static int randomInt(int upper)
	{
		Random random = new Random();
		return random.nextInt(upper);
	}
}


CloudSignHelper.java

import java.io.CharArrayReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import java.util.zip.Deflater;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.Arrays;
import com.alibaba.fastjson.JSONObject;
//import com.tls.base64_url.base64_url;

public class CloudSignHelper 
{
	private final static String privStr = "<密钥>";
	
	private final static long skdAppid = <appid>;
	public static String GetSign(String uid)
	{
		 GenTLSSignatureResult result = null;
		try{
			//生成签名
            result = GenTLSSignatureEx(skdAppid, uid, privStr);
            if (0 == result.urlSig.length()) {
                System.out.println("GenTLSSignatureEx failed: " + result.errMessage);
                return null;
            }	
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result.urlSig;
	}
	
	/**
	 * @brief 生成 tls 票据,精简参数列表,有效期默认为 180 天
	 * @param skdAppid 应用的 sdkappid
	 * @param identifier 用户 id
	 * @param privStr 私钥文件内容
	 * @return
	 * @throws IOException
	 */
	private static  GenTLSSignatureResult GenTLSSignatureEx(
			long skdAppid,
			String identifier,
			String privStr) throws IOException {
		return GenTLSSignatureEx(skdAppid, identifier, privStr, 3600*24*180);
	}
	
	/**
	 * @brief 生成 tls 票据,精简参数列表
	 * @param skdAppid 应用的 sdkappid
	 * @param identifier 用户 id
	 * @param privStr 私钥文件内容
	 * @param expire 有效期,以秒为单位,推荐时长一个月
	 * @return
	 * @throws IOException
	 */
	private static  GenTLSSignatureResult GenTLSSignatureEx(
			long skdAppid,
			String identifier,
			String privStr,
			long expire) throws IOException {

		GenTLSSignatureResult result = new GenTLSSignatureResult();
		
        Security.addProvider(new BouncyCastleProvider());
        Reader reader = new CharArrayReader(privStr.toCharArray());
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        PEMParser parser = new PEMParser(reader);
        Object obj = parser.readObject();
        parser.close();
    	PrivateKey privKeyStruct = converter.getPrivateKey((PrivateKeyInfo) obj);
		
		String jsonString = "{" 
		+ "\"TLS.account_type\":\"" + 0 +"\","
		+"\"TLS.identifier\":\"" + identifier +"\","
		+"\"TLS.appid_at_3rd\":\"" + 0 +"\","
	    +"\"TLS.sdk_appid\":\"" + skdAppid +"\","
		+"\"TLS.expire_after\":\"" + expire +"\","
        +"\"TLS.version\": \"201512300000\""
		+"}";
		
		String time = String.valueOf(System.currentTimeMillis()/1000);
		String SerialString = 
			"TLS.appid_at_3rd:" + 0 + "\n" +
			"TLS.account_type:" + 0 + "\n" +
			"TLS.identifier:" + identifier + "\n" + 
			"TLS.sdk_appid:" + skdAppid + "\n" + 
			"TLS.time:" + time + "\n" +
			"TLS.expire_after:" + expire +"\n";
		
		try {
			//Create Signature by SerialString
			Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
			signature.initSign(privKeyStruct);
			signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
			byte[] signatureBytes = signature.sign();
			
			String sigTLS = Base64.encodeBase64String(signatureBytes);
			
			//Add TlsSig to jsonString
			JSONObject jsonObject= JSONObject.parseObject(jsonString);
		    jsonObject.put("TLS.sig", (Object)sigTLS);
		    jsonObject.put("TLS.time", (Object)time);
		    jsonString = jsonObject.toString();
		    
		    //compression
		    Deflater compresser = new Deflater();
		    compresser.setInput(jsonString.getBytes(Charset.forName("UTF-8")));

		    compresser.finish();
		    byte [] compressBytes = new byte [512];
		    int compressBytesLength = compresser.deflate(compressBytes);
		    compresser.end();
		    String userSig = new String(base64_url.base64EncodeUrl(Arrays.copyOfRange(compressBytes,0,compressBytesLength)));
    
		    result.urlSig = userSig;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			result.errMessage = "generate usersig failed";
		}
		
		return result;
	}
}

GenTLSSignatureResult.java

public class GenTLSSignatureResult 
{
	public String errMessage;
	public String urlSig;
	public int expireTime;
	public int initTime;
	public GenTLSSignatureResult()
	{
		errMessage = "";
		urlSig = "";
	}
}

base64_url.java

注: jdk1.7需要手动添加此类; jdk1.8可以加载tls_sig_api.jar中的base64_url.java,不需要手动添加.

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.util.Arrays;

public class base64_url {
	static  byte base64_table_url[] =
    { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
      'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
      'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '-', '\0'};

	static  byte base64_pad_url = '_';

	static  short base64_reverse_table_url[] = {
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, 63, -1, -1,
	    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
	    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
	    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
	    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
	    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
	};
	
	public static int unsignedToBytes(int b)
	{
		return b & 0xFF;
	}

	//int base64_encode_url(const unsigned char *in_str, int length, char *out_str,int *ret_length)
	public static byte [] base64EncodeUrl(byte [] in_str)
	{
		byte [] out_str = new byte [1024] ;

	    int out_current = 0;
	    int current = 0;
	    int length = in_str.length;

	    while (length > 2) { /* keep going until we have less than 24 bits */
	    	 
	    	out_str[out_current++] = base64_table_url[unsignedToBytes((unsignedToBytes(in_str[current]) >>> 2))];
	    	out_str[out_current++] = base64_table_url[unsignedToBytes(unsignedToBytes(unsignedToBytes(in_str[current]) & 0x03) << 4) + unsignedToBytes((unsignedToBytes(in_str[current+1]) >>> 4))];
	    	out_str[out_current++] = base64_table_url[(unsignedToBytes((unsignedToBytes(in_str[current+1]) & 0x0f)) << 2) + unsignedToBytes((unsignedToBytes(in_str[current+2]) >>> 6))];
	    	out_str[out_current++] = base64_table_url[unsignedToBytes((unsignedToBytes(in_str[current+2]) & 0x3f))];
	        current += 3;
	        length -= 3; /* we just handle 3 octets of data */
	    }

	    /* now deal with the tail end of things */
	    if (length != 0) {
	    	out_str[out_current++] = base64_table_url[unsignedToBytes(in_str[current]) >>> 2];
	        if (length > 1) {
	        	out_str[out_current++] = base64_table_url[unsignedToBytes((unsignedToBytes(in_str[current]) & 0x03) << 4) + unsignedToBytes(unsignedToBytes(in_str[current+1]) >>> 4)];
	        	out_str[out_current++] = base64_table_url[unsignedToBytes((unsignedToBytes(in_str[current + 1]) & 0x0f) << 2)];
	        	out_str[out_current++] = base64_pad_url;
	        } else {
	        	out_str[out_current++] = base64_table_url[unsignedToBytes((unsignedToBytes(in_str[current]) & 0x03) << 4)];
	        	out_str[out_current++] = base64_pad_url;
	        	out_str[out_current++] = base64_pad_url;
	        }
	    }
	    
        //System.out.println("length in base64EncodeUrl: " + out_current );
	    byte [] out_bytes = new String(out_str).getBytes(); 
	    return Arrays.copyOfRange(out_bytes, 0, out_current);
	}

	//int base64_decode_url(const unsigned char *in_str, int length, char *out_str, int *ret_length)
	public static byte [] base64DecodeUrl(byte [] in_str)
	{
	//        const unsigned char *current = in_str;
	        int ch, i = 0, j = 0, k;
	        
	        int current  = 0;
	        byte [] out_str = new byte [1024] ;
			int length = in_str.length;
	        /* this sucks for threaded environments */

	        /* run through the whole string, converting as we go */
	        //while ((ch = in_str[current++]) != '\0' && length-- > 0) {
			ch = in_str[0];
			while(length-- > 0){
					ch = in_str[current++];
	                if (ch == base64_pad_url) break;
	                /* When Base64 gets POSTed, all pluses are interpreted as spaces.
	                   This line changes them back.  It's not exactly the Base64 spec,
	                   but it is completely compatible with it (the spec says that
	                   spaces are invalid).  This will also save many people considerable
	                   headache.  - Turadg Aleahmad <turadg@wise.berkeley.edu>
	            */
	                if (ch == ' ') ch = '*'; //never using '+'

	                ch = base64_reverse_table_url[ch];
	                if (ch < 0) continue;

	                switch(i % 4) {
	                case 0:
	                	out_str[j] = (byte) unsignedToBytes( unsignedToBytes(ch) << 2);
	                    break;
	                case 1:
	                	out_str[j++] |= (byte) unsignedToBytes(unsignedToBytes(ch) >>> 4);
	                	out_str[j] = (byte) unsignedToBytes(unsignedToBytes(unsignedToBytes(ch) & 0x0f) << 4);
	                    break;
	                case 2:
	                	out_str[j++] |= (byte) unsignedToBytes(unsignedToBytes(ch) >>> 2);
	                	out_str[j] = (byte) unsignedToBytes(unsignedToBytes(unsignedToBytes(ch) & 0x03) << 6);
	                    break;
	                case 3:
	                	out_str[j++] |= (byte) unsignedToBytes(ch);
	                    break;
	                }
	                i++;
	        }
	        k = j;
	        /* mop things up if we ended on a boundary */
	        if (ch == base64_pad_url) { 	
	                switch(i % 4) {
	                case 0:
	                case 1:
	                        byte [] error =  new byte [1];
	                        error[0] = '\0';
	                        return error;
	                case 2:
	                    k++;
	                case 3:
	                	out_str[k++] = 0;
	                }
	        }
		    return Arrays.copyOfRange(out_str, 0, j);
	}
	public static void main(String[] args) throws DecoderException {
		
		//String hexString = "5095";
		String hexString = "789c6d8d4d4f83401884ff0b578c5dba0bbb98782015b1a1f8059a7222743fc8da96aecbdbdad6f8dfa5046fce6de6c9cc7c3bc522bfeec4baaa8dd1c2b9713c822e0a7ddfb91aa03c1a6d65552b90b6e794d2a0e7231c5a550d15b6ff96416fe590e38051c2281d732d640b5ae96172ea051c29be524c62e463e57382e854a08020a578c8febe38dfed5ba8e0642e9b98e21174bae97d16bfcde633299e0f49c81f27a26490b97665d7675dd0fdc35df1de994d23bc4301db349fbb918ea3e36b509878f7956d84dbb44b4ed23287b454f7119c12fea4968b64927d7c962179b9757e7e01ed1059d9";
		
		byte [] test = Hex.decodeHex(hexString.toCharArray());
		byte [] compressBytes = base64EncodeUrl(test);
		System.out.println("compress : " + new String(compressBytes));
		byte [] uncompressBytes = base64DecodeUrl(compressBytes);
		System.out.println("uncompress: " + Hex.encodeHexString(uncompressBytes));
	}
}

UserInfo.java

public class UserInfo {
	private String nickname = "";//昵称
	private String image = "";//头像
	private Byte sex = null;//性别
	
	public String getNickname() {
		return nickname;
	}
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
	public String getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public Byte getSex() {
		return sex;
	}
	public void setSex(Byte sex) {
		this.sex = sex;
	}
	public UserInfo(String nickname, String image, Byte sex) {
		super();
		this.nickname = nickname;
		this.image = image;
		this.sex = sex;
	}
	public UserInfo() {
		super();
	}
}

FriendInfo.java

public class FriendInfo {
	private long fuid;//好友uid
	private String nickname;//昵称
	private String remark;//备注
	private String image;//头像
	
	public long getFuid() {
		return fuid;
	}
	public void setFuid(long fuid) {
		this.fuid = fuid;
	}
	public String getNickname() {
		return nickname;
	}
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public String getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}	
}

Demo.java 测试

import org.junit.Test;
import utils.TXCloudUtils;
import utils.UserInfo;

public class Demo {
	@Test 
	public void account() {
		byte result = TXCloudUtils.AccountImport(2003, "lucy", "https://www.baidu.com/img/bd_logo1.png");
		System.out.println(result);
	}
	
	@Test
	public void OpenimSendMsg() {
		byte result = TXCloudUtils.OpenimSendMsg(1001, "hello lucy!!");
		System.out.println(result);
	}
	
	@Test
	public void ImPush() {
		byte result = TXCloudUtils.ImPush("hello everybody!");
		System.out.println(result);
	}
	
	@Test
	public void setPortrait() {
		UserInfo userInfo = new UserInfo("lucy1", "http://fanyi.baidu.com/static/translation/img/header/downloadGuide/baidu_b76f076.png", (byte)0);
		boolean result = TXCloudUtils.setPortrait(1001L, userInfo);
		System.out.println(result);
	}
	
	@Test
	public void getPortrait() {
		String result = TXCloudUtils.getPortrait(1001L);
		System.out.println(result);
	}
	
	@Test
	public void addFriend() {
		byte result = TXCloudUtils.addFriend(1001, 2002, "myfriend2", "Android");
		System.out.println(result);
	}
	
	@Test
	public void deleteFriend() {
		byte result = TXCloudUtils.deleteFriend(1001, 2002);
		System.out.println(result);
	}
	
	@Test
	public void checkFriend() {
		byte result = TXCloudUtils.checkFriend(1001, 2002);
		System.out.println(result);
	}
	
	@Test
	public void getOneFriend() {
		String friend = TXCloudUtils.getOneFriend(1001, 2002);
		System.out.println(friend);
	}
	
	@Test
	public void getAllFriend() {
		String result = TXCloudUtils.getAllFriend(1001, 0);
		System.out.println(result);
	}
}




  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值