微信长链接转短链接

最近微信除了公告6月2号,限制短链接调用次数为10次。
在这里插入图片描述
业务需求,需要把长链接转为短链接,再生成二维码,减少二维码密度,提高用户扫码效率。

1、工具类:MD5Util(网上找的md5加密工具类)

package com.bycotrun.platform.utils;

import java.security.MessageDigest;

/**
 *
 * 项目名称:dmsys 类名称:MD5Util 类描述: 创建人: 创建时间:2020年5月21日 下午2:26:04 修改人:
 * 修改时间:2020年5月21日 下午2:26:04 修改备注:
 * 
 * @version
 *
 */
public class MD5Util {
    // MD5加码。32位
    public static String MD5(String inStr) {
	MessageDigest md5 = null;
	try {
	    md5 = MessageDigest.getInstance("MD5");
	} catch (Exception e) {
	    System.out.println(e.toString());
	    e.printStackTrace();
	    return "";
	}
	char[] charArray = inStr.toCharArray();
	byte[] byteArray = new byte[charArray.length];

	for (int i = 0; i < charArray.length; i++)
	    byteArray[i] = (byte) charArray[i];

	byte[] md5Bytes = md5.digest(byteArray);

	StringBuffer hexValue = new StringBuffer();

	for (int i = 0; i < md5Bytes.length; i++) {
	    int val = ((int) md5Bytes[i]) & 0xff;
	    if (val < 16)
		hexValue.append("0");
	    hexValue.append(Integer.toHexString(val));
	}

	return hexValue.toString();
    }

    // 可逆的加密算法
    public static String KL(String inStr) {
	// String s = new String(inStr);
	char[] a = inStr.toCharArray();
	for (int i = 0; i < a.length; i++) {
	    a[i] = (char) (a[i] ^ 't');
	}
	String s = new String(a);
	return s;
    }

    // 加密后解密
    public static String JM(String inStr) {
	char[] a = inStr.toCharArray();
	for (int i = 0; i < a.length; i++) {
	    a[i] = (char) (a[i] ^ 't');
	}
	String k = new String(a);
	return k;
    }

    // 测试主函数
    public static void main(String args[]) {
	String s = new String("a");
	System.out.println("原始:" + s);
	System.out.println("MD5后:" + MD5(s));
	System.out.println("MD5后再加密:" + KL(MD5(s)));
	System.out.println("解密为MD5后的:" + JM(KL(MD5(s))));
	System.out.println("判断是否相同:" + MD5(s).equals(JM(KL(MD5(s)))));
    }

}

2、GetUrl类(生成短链接)

package com.bycotrun.platform.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bycotrun.framework.dao.BaseDao;
import com.bycotrun.framework.utils.IdGenerator;
import com.bycotrun.platform.po.WxShortLongUrl;

@Component
public class GetUrl {
    private static BaseDao baseDao;
    @Autowired
    private BaseDao baseDao1;

    @PostConstruct
    public void init() {
	baseDao = baseDao1;
    }

    // 长链接转短链接(本地实现,不调用微信接口)
    public static String getShortUrl(String longurl, String ACCESS_TOKEN) {
	// 获取请求域名
	String longurl2 = "";
	try {
	    longurl2 = URLDecoder.decode(longurl, "UTF-8");// utf-8解码
	} catch (UnsupportedEncodingException e) {
	    e.printStackTrace();
	}
	// 获取/下标
	int inde = longurl2.indexOf("redirect_uri=");
	for (int i = 0; i < 4; i++) {
	    inde = longurl2.indexOf("/", inde + 1);
	}
	String url = longurl2.substring(longurl2.indexOf("redirect_uri=") + 13, inde);

	String outChars = "";// 短链接字段
	// **************生成开始**********************
	int size = 0;
	do {
	    // 可以自定义生成 MD5 加密字符传前的混合 KEY
	    String key = "caron";
	    // 要使用生成 URL 的字符
	    String[] chars = new String[] { "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", "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"

	    };
	    // 对传入网址进行 MD5 加密
	    String sMD5EncryptResult = MD5Util.MD5(key + longurl);
	    String hex = sMD5EncryptResult;

	    // 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算
	    String sTempSubString = hex.substring(2 * 8, 2 * 8 + 8); // 固定取第三组

	    // 这里需要使用 long 型来转换,因为 Inteper .parseInt() 只能处理 31 位 , 首位为符号位 , 如果不用 long ,则会越界
	    long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
	    for (int j = 0; j < 6; j++) {
		// 把得到的值与 0x0000003D 进行位与运算,取得字符数组 chars 索引
		long index = 0x0000003D & lHexLong;
		// 把取得的字符相加
		outChars += chars[(int) index];
		// 每次循环按位右移 5 位
		lHexLong = lHexLong >> 5;
	    }
	    // 数据获取一个字母增加随机性
	    Random rand = new Random();
	    int idx = rand.nextInt(32);
	    outChars += chars[idx];
	    // 判断短链接是否重复
	    List list = baseDao.getList("SELECT ws.id FROM `wx_short_long_url` ws WHERE ws.shorturl='" + outChars + "'",
		    null);
	    size = list.size();
	} while (size > 0);
	// **************生成结束**********************
	// 拼接短链接
	url = url + "/s/" + outChars;
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("id", IdGenerator.generateStr());
	map.put("shorturl", outChars);
	map.put("longurl", longurl);
	try {
	    baseDao.insert(WxShortLongUrl.class, map);
	} catch (Exception e) {
	    System.out.println("添加短链接关联表失败");
	}
	System.out.println("短链接:" + url);
	return url;
    }
}

3、Controller层调用

package com.bycotrun.platform.web;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.bycotrun.framework.dao.BaseDao;
import com.bycotrun.framework.utils.ValidateUtil;
import com.bycotrun.platform.po.WxShortLongUrl;

/**
 *
 * 项目名称:dmsys 类名称:WxShortUrlRedirectLongUrlAction 类描述:微信短链接重定向长链接 创建人:
 * 创建时间:2020年5月21日 下午3:00:10 修改人: 修改时间:2020年5月21日 下午3:00:10 修改备注:
 * 
 * @version
 *
 */
@Controller
@RequestMapping("/s")
public class WxShortUrlRedirectLongUrlAction {
    @Autowired
    BaseDao baseDao;

    // 短链接跳转
    @RequestMapping(value = "/{shorturl}", method = RequestMethod.GET)
    public ModelAndView deptDefault(@PathVariable("shorturl") String url, HttpServletResponse response)
	    throws IOException {
	response.setContentType("text/html;charset=UTF-8");
	response.setCharacterEncoding("UTF-8");
	response.setHeader("Access-Control-Allow-Origin", "*");
	if (!ValidateUtil.isNull(url)) {
	    WxShortLongUrl longurl = baseDao.query(WxShortLongUrl.class, "shorturl='" + url + "'", null);
	    if (!ValidateUtil.isNull(longurl)) {
		System.out.println("请求长链接"+longurl.getLongurl());
		response.sendRedirect(longurl.getLongurl());
		return null;
	    }
	}
	return new ModelAndView("/market/newBargin/erro");
    }
}

参考:
https://blog.csdn.net/u013782879/article/details/80851784

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值