现在,这并不是严格意义上的 URL 缩短,但无论如何我的目的是这样的,所以让我们这样看待它。当然 URL 缩短的步骤是:
- 获取完整的 URL
- 生成唯一的短字符串作为 URL 的键
- 将 URL 和键存储在数据库中(键值存储将是完美的匹配)
现在,关于第二点。这是我想出的:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
UUID uuid = UUID.randomUUID();
dos.writeLong(uuid.getMostSignificantBits());
String encoded = new String(Base64.encodeBase64(baos.toByteArray()), "ISO-8859-1");
String shortUrlKey = StringUtils.left(encoded, 6); // returns the leftmost 6 characters
// check if exists in database, repeat until it does not
这够好吗?