短网址

Posted 麦德漂

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了短网址相关的知识,希望对你有一定的参考价值。

短网址就是很简短的网址,目前有两种实现方式。1.自有短网址域名或第三方,生成短网址后,自动解析。2.生成短网址后,保存短网址与原网址映射关系,由本系统域名对外转发并跳转。使用第二种方法实现方式如下:

 1 public class ShortUrl { 
 2     public static String ShortText(String originalUrl){ 
 3         String key = "com.maidepiao";                
 4         String[] chars = new String[]{         
 5             "a","b","c","d","e","f","g","h", 
 6             "i","j","k","l","m","n","o","p", 
 7             "q","r","s","t","u","v","w","x", 
 8             "y","z","0","1","2","3","4","5", 
 9             "6","7","8","9","A","B","C","D", 
10             "E","F","G","H","I","J","K","L", 
11             "M","N","O","P","Q","R","S","T", 
12             "U","V","W","X","Y","Z" 
13         }; 
14         String hex = Encript.md5(key + originalUrl); 
15         int hexLen = hex.length(); 
16         int subHexLen = hexLen / 8; 
17         String[] ShortStr = new String[4]; 
18          
19         for (int i = 0; i < subHexLen; i++) { 
20             String outChars = ""; 
21             int j = i + 1; 
22             String subHex = hex.substring(i * 8, j * 8); 
23             long idx = Long.valueOf("3FFFFFFF", 16) & Long.valueOf(subHex, 16); 
24              
25             for (int k = 0; k < 6; k++) { 
26                 int index = (int) (Long.valueOf("0000003D", 16) & idx); 
27                 outChars += chars[index]; 
28                 idx = idx >> 5; 
29             } 
30             ShortStr[i] = outChars; 
31         } 
32         Random random=new Random();
33         int j=random.nextInt(4);
34         /**
35          * 将短连接与原链接的映射关系保存至redis,由系统向外重定向
36          */
37         JedisUtils.set("shortURL:"+ShortStr[j], originalUrl, 0);
38         return ShortStr[j]; 
39     } 
40 } 

生成短连接后,根据短连接码请求自有系统,和普通的request一样,然后重定向跳转原路径

 1 @Controller
 2 @RequestMapping("")
 3 public class ShortUrlRoute extends BaseController{
 4     //private static final Logger logger = LogManager.getLogger(ShortUrlRoute.class);
 5     
 6     @RequestMapping(value= "/{shortUrlKey}" )  
 7     public String message(@PathVariable String shortUrlKey,HttpServletRequest request,HttpServletResponse response) {
 8         return "redirect:"+JedisUtils.get("shortURL:"+shortUrlKey,"");
 9     }
10 }

采用的是springMVC请求,使用redis作为中间的载体,请求短网址时,根据短网址在redis找到原路径,然后跳转即可。

 

以上是关于短网址的主要内容,如果未能解决你的问题,请参考以下文章

PHP WP短代码 - 检索作者页面网址

python3 短网址和数字的相互转换的代码

php 两种短网址生成方法

如何从片段内的列表视图打开链接网址?

php Wordpress:联系表格7,添加表格标签(短代码)当前网址示例

怎么把链接变短