10.小程序工具类

10.小程序工具类

/**
 * 向指定 URL 发送POST方法的请求
 * 
 * @param url
 *            发送请求的 URL
 * @param param
 *            请求参数
 * @return 所代表远程资源的响应结果
 */
public synchronized static String sendPost(String url, Map<String, ?> paramMap) {
	PrintWriter out = null;
	BufferedReader in = null;
	String result = "";

	String param = "";
	Iterator<String> it = paramMap.keySet().iterator();

	while (it.hasNext()) {
		String key = it.next();
		param += key + "=" + paramMap.get(key) + "&";
	}
	try {
		URL realUrl = new URL(url);
		// 打开和URL之间的连接
		URLConnection conn = realUrl.openConnection();
		// 设置通用的请求属性
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("Accept-Charset", "utf-8");
		conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		// 发送POST请求必须设置如下两行
		conn.setDoOutput(true);
		conn.setDoInput(true);
		// 获取URLConnection对象对应的输出流
		out = new PrintWriter(conn.getOutputStream());
		// 发送请求参数
		out.print(param);
		// flush输出流的缓冲
		out.flush();
		// 定义BufferedReader输入流来读取URL的响应
		in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
		String line;
		while ((line = in.readLine()) != null) {
			result += line;
		}
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	}
	// 使用finally块来关闭输出流、输入流
	finally {
		try {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				in.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	return result;
}
/**
 * 发送post请求 
 * 
 * @param url
 * 			发送请求的 URL
 * 
 * @param param
 * 			请求参数 json格式
 * 
 * @return 
 * 
 * */
public synchronized static String sendPostJson(String url, String param) {
	
	PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection conn = realUrl.openConnection();
        // 设置通用的请求属性
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Content-Type", "application/json");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        out = new PrintWriter(conn.getOutputStream());
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        log.info("发送 POST 请求出现异常!" + e);
        e.printStackTrace();
    }
    //使用finally块来关闭输出流、输入流
    finally{
        try{
            if(out!=null){
                out.close();
            }
            if(in!=null){
                in.close();
            }
        }
        catch(IOException ex){
            ex.printStackTrace();
        }
    }                                                              
    return result;	
}
/**
 * 获取微信小程序 session_key 和 openid
 * 
 * @param code 调用微信登陆返回的Code
 * @param appid 标识
 * @param secret 密钥 
 * 
 * @return JSONObject
 */
public synchronized static JSONObject getSessionKeyOropenid(String code, String appid, String secret) {
	// 微信端登录code值
	String wxCode = code;
	String requestUrl = "https://api.weixin.qq.com/sns/jscode2session"; // 请求地址

	Map<String, String> requestUrlParam = new HashMap<String, String>();
	requestUrlParam.put("appid", appid); // 开发者设置中的appId
	requestUrlParam.put("secret", secret); // 开发者设置中的appSecret
	requestUrlParam.put("js_code", wxCode); // 小程序调用wx.login返回的code
	requestUrlParam.put("grant_type", "authorization_code"); // 默认参数

	// 接口获取openid用户唯一标识 发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session
	JSONObject jsonObject = JSON.parseObject(sendPost(requestUrl, requestUrlParam));
	return jsonObject;
}
// sendPost 为一个请求各种接口而封装的函数,并转换JSON字符串为JSONObject
private static String getAccessToken(String accessTokenURL, Map<String, String> requestParam) {
	String access_token;
	JSONObject jsonObject = JSON.parseObject(sendPost(accessTokenURL, requestParam));
	access_token = jsonObject.getString("access_token");
	
	return access_token;
}
/**
 * 获取微信小程序 accessToken
 * 
 * @param appid 标识
 * @param secret 密钥 
 * 
 * @return access_token
 */
public synchronized static String getSessionKeyOropenid(String appid, String secret) {
	String accessTokenURL = "https://api.weixin.qq.com/cgi-bin/token";
	Map<String, String> requestParam = new HashMap<String, String>();
	requestParam.put("grant_type", "client_credential");
	requestParam.put("appid", appid);
	requestParam.put("secret", secret);
	
	return getAccessToken(accessTokenURL, requestParam);
}
/**
 * 解密用户敏感数据获取用户信息
 * 
 * @param sessionKey 数据进行加密签名的密钥
 * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
 * @param iv 加密算法的初始向量
 *            
 * @return JSONObject
 */
public synchronized static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
	// 被加密的数据
	byte[] dataByte = Base64.decode(encryptedData);
	// 加密秘钥
	byte[] keyByte = Base64.decode(sessionKey);
	// 偏移量
	byte[] ivByte = Base64.decode(iv);
	try {
		// 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
		int base = 16;
		if (keyByte.length % base != 0) {
			int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
			byte[] temp = new byte[groups * base];
			Arrays.fill(temp, (byte) 0);
			System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
			keyByte = temp;
		}
		// 初始化
		Security.addProvider(new BouncyCastleProvider());
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
		SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
		AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
		parameters.init(new IvParameterSpec(ivByte));
		cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
		byte[] resultByte = cipher.doFinal(dataByte);
		if (null != resultByte && resultByte.length > 0) {
			String result = new String(resultByte, "UTF-8");
			return JSON.parseObject(result);
		}
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	}
	return null;
}
/**
 * 获取小程序二维码图片
 * 
 * @param accessToken 访问令牌
 * @param serviceCode 参数
 * @param picPath 二维码图片路径
 * @param path 扫描二维码后跳转的页面
 * 
 * @return Boolean;
 */
public synchronized static Boolean getminiqrQr(String accessToken, String serviceCode, String picPath, String path) {
	try {
		URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setRequestMethod("POST");// 提交模式
		// conn.setConnectTimeout(10000);//连接超时 单位毫秒
		// conn.setReadTimeout(2000);//读取超时 单位毫秒
		// 发送POST请求必须设置如下两行
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setDoInput(true);
		// 获取URLConnection对象对应的输出流
		PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
		// 发送请求参数
		JSONObject paramJson = new JSONObject();
		paramJson.put("scene", serviceCode);// 这就是你二维码里携带的参数 String型 名称不可变
		paramJson.put("page", path); // 这是设置扫描二维码后跳转的页面
		paramJson.put("width", 430);
		paramJson.put("is_hyaline", false);
		paramJson.put("auto_color", false);

		System.out.println("httpURLConnection" + httpURLConnection);
		System.out.println("paramJson.toString()" + paramJson.toString());

		printWriter.write(paramJson.toString());
		// flush输出流的缓冲
		printWriter.flush();
		// 开始获取数据
		BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
		OutputStream os = new FileOutputStream(new File(picPath));
		int len;
		byte[] arr = new byte[1024];
		while ((len = bis.read(arr)) != -1) {
			os.write(arr, 0, len);
			os.flush();
		}
		os.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return true;
}
/**
 * 生成小程序二维码图片
 * 
 * @param paramete 参数
 * @param appid 秘钥
 * @param secret 秘钥
 * @param page 小程序页面路径
 * 
 * @return imgUrl
 */
public synchronized static String codeImage(String paramete, String appid, String secret, String page) {
	String picPathDir = "/upload/oldPushCode";
	File picFoler = new File(picPathDir);
	if (!picFoler.exists()) {
		picFoler.mkdirs();
	}
	String picPath = picPathDir + "/" + paramete + ".png";

	String accessToken = XcxUtils.getSessionKeyOropenid(appid, secret);
	String path = page;
	String scene = paramete;
	getminiqrQr(accessToken, scene, picPath, path);
	
	String image = "/upload/oldPushCode/" + paramete + ".png";

	return image;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值