java执行linux命令:head -n 80 /dev/urandom | tr -dc A-Za-z0-9 | head -c 168

时间:2022-06-01 18:38:27

 看了微信小程序api后,发现登录Logo接口需要处理随机key,所以着手处理了一下。  

直接贴代码:

    //先运行命令,让其生成168位随机数
private static String wxSessionkey = "F3UENUg3JcI31O2RpoBQ9n8J77Tf1LgZUyGyzdjm7Q4rRKT052DPLdA3NqHeajF6cITOX54rQ2yoFxE83g3eHWjEH7CB9m2FvdoljuTXZLrJy6U2Ba2EbUlF6xazawRaK9Aq";

/**
* linux中执行命令
* @param cmd
* @return
*/
public static String exec(String cmd) {
StringBuffer sb = new StringBuffer();
try {
String[] cmdA = { "/bin/sh", "-c", cmd };
Process process = Runtime.getRuntime().exec(cmdA);
LineNumberReader br = new LineNumberReader(new InputStreamReader(
process.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (Exception e) {
//如果本地测试,会报空指针异常,所以为了不让报错,索性返回有值即可
sb.append(wxSessionkey);
}
return sb.toString();
}

然后调用即可:

    /**
* 得到3rd_session登录效验(key)
* @return
*/
public String get3rdSession(){
return exec("head -n 80 /dev/urandom | tr -dc A-Za-z0-9 | head -c 168");
}

最后,在memcache中使用这个随机数key

    public void putSession(WxUser u) {
BeanManager.getSpyMemcachedClient().set(wxSessionkey, 3*24*3600,u.getOpenid()+","+u.getSession_key());//设置memcache缓存
}