跟app端对接,接入融云im,需要我们后台提供token,看融云api,说实话感觉不像给人看的,找了很多的资料,才整理出来,希望对看到这篇文章的小伙伴有点帮助
代码如下
/**
* rongToken
* @param userId 用户id
* @param avatar 用户头像
* @param nickname 用户昵称
* @return
*/
public String getRongToken(String userId,String avatar ,String nickname) {
StringBuffer res = new StringBuffer();
String url = "https://api.cn.ronghub.com/user/getToken.json";
String App_Key = "********"; //开发者平台分配的 App Key。
String App_Secret = "******";
String Timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳,从 1970 年 1 月 1 日 0 点 0 分 0 秒开始到现在的秒数。
String Nonce = String.valueOf(Math.floor(Math.random() * 1000000));//随机数,无长度限制。
StringBuilder toSign = new StringBuilder(App_Secret).append(Nonce).append(Timestamp);
String Signature = CodeUtil.hexSHA1(toSign.toString());//数据签名。
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("App-Key", App_Key);
httpPost.setHeader("Timestamp", Timestamp);
httpPost.setHeader("Nonce", Nonce);
httpPost.setHeader("Signature", Signature );
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<BasicNameValuePair> nameValuePair = new ArrayList<>(1);
nameValuePair.add(new BasicNameValuePair("userId", userId));
nameValuePair.add(new BasicNameValuePair("name",nickname));
nameValuePair.add(new BasicNameValuePair("portraitUri",avatar));
HttpResponse httpResponse = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,"utf-8"));
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse result = httpClient.execute(httpPost);
BufferedReader br = new BufferedReader(new InputStreamReader(result.getEntity().getContent()));
String line = null;
while ((line = br.readLine()) != null) {
res.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
JSONObject object = JSON.parseObject(res.toString());
return object.getString("token");
}
SHA1生成
/**
* SHA1加密
*/
public class CodeUtil {
public static String hexSHA1(String value) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(value.getBytes("utf-8"));
byte[] digest = md.digest();
return byteToHexString(digest);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static String byteToHexString(byte[] bytes) {
return String.valueOf(Hex.encodeHex(bytes));
}
}
到此完结,可以直接运行啦!