生成思路:
1.将"原始链接(长链接)+key(自定义字符串,防止算法泄漏)"MD5加密
2.把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算,把得到的值与 0x0000003D 进行位与运算,取得字符数组 chars 索引,把取得的字符相加,每次循环按位右移 5 位,把字符串存入对应索引的输出数组(4组6位字符串)
3.生成4以下的随机数,从输入数组中取出随机数对应位置的字符串,作为短链,存入数据库或者NoSql
解析方式
编写一个web处理程序,把从ur(如:http://url.51bi.com/zAnuAn)中解析短链接,将解析到的短链接(zAnuAn)与数据库中存入的原始链接进行匹配,跳转到匹配到的原始链接。
package com.bjdata.test;
import java.security.MessageDigest;
import java.util.Random;
public class ShortUrlTest {
public static void main(String[] args) {
String sLongUrl = "http://www.51bi.com/bbs/_t_278433840/"; // 原始链接
System.out.println("长链接:"+sLongUrl);
String[] aResult = shortUrl(sLongUrl);//将产生4组6位字符串
// 打印出结果
for (int i = 0; i < aResult.length; i++) {
System.out.println("[" + i + "]:" + aResult[i]);
}
Random random=new Random();
int j=random.nextInt(4);//产成4以内随机数
System.out.println("短链接:"+aResult[j]);//随机取一个作为短链
}
public static String[] shortUrl(String url) {
// 可以自定义生成 MD5 加密字符传前的混合 KEY
String key = "test";
// 要使用生成 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 hex = md5ByHex(key + url);
String[] resUrl = new String[4];
for (int i = 0; i < 4; i++) {
// 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算
String sTempSubString = hex.substring(i * 8, i * 8 + 8);
// 这里需要使用 long 型来转换,因为 Inteper .parseInt() 只能处理 31 位 , 首位为符号位 , 如果不用long ,则会越界
long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
String outChars = "";
for (int j = 0; j < 6; j++) {
// 把得到的值与 0x0000003D 进行位与运算,取得字符数组 chars 索引
long index = 0x0000003D & lHexLong;
// 把取得的字符相加
outChars += chars[(int) index];
// 每次循环按位右移 5 位
lHexLong = lHexLong >> 5;
}
// 把字符串存入对应索引的输出数组
resUrl[i] = outChars;
}
return resUrl;
}
/**
* MD5加密(32位大写)
* @param src
* @return
*/
public static String md5ByHex(String src) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] b = src.getBytes();
md.reset();
md.update(b);
byte[] hash = md.digest();
String hs = "";
String stmp = "";
for (int i = 0; i < hash.length; i++) {
stmp = Integer.toHexString(hash[i] & 0xFF);
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
} catch (Exception e) {
return "";
}
}
}
运行结果
长链接:http://www.51bi.com/bbs/_t_278433840/ [0]:fa6bUr [1]:ryEfeq [2]:zAnuAn [3]:auIJne 短链接:zAnuAn
分享sina的短链生成java代码
比如可以将http://zuidaima.com/转换为http://t.cn/zlsvWVq
如下图:
package com.zuidaima.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ShortenUrl {
private static final boolean DEBUG = true;
public static void main(String[] args) {
String url = "http://www.henshiyong.com/tools/sina-shorten-url.php";
Map<String, String> params = new LinkedHashMap<String, String>();
params.put("url", "http://www.google.com");
params.put("submit", "转换");
String data = null;
try {
data = postUrl(url, params);
if (DEBUG) {
System.out.println(data);
}
} catch (IOException ex) {
}
if (data != null) {
String shortUrl = getShortenUrl(data);
if (DEBUG) {
System.out.println(shortUrl);
}
}
}
public static String getShortenUrl(String content) {
String url = null;
List<String> resultList = getContext(content);
for (Iterator<String> iterator = resultList.iterator(); iterator
.hasNext();) {
url = iterator.next();
}
return url;
}
/**
* Extract "XXXX" from "<textarea>XXXX</textarea>"
*
* @param html
* @return
*/
public static List<String> getContext(String html) {
List<String> resultList = new ArrayList<String>();
Pattern p = Pattern.compile("<textarea>(.*)</textarea>");
Matcher m = p.matcher(html);
while (m.find()) {
resultList.add(m.group(1));
}
return resultList;
}
public static class HttpException extends RuntimeException {
private int errorCode;
private String errorData;
public HttpException(int errorCode, String errorData) {
super("HTTP Code " + errorCode + " : " + errorData);
this.errorCode = errorCode;
this.errorData = errorData;
}
public int getErrorCode() {
return errorCode;
}
public String getErrorData() {
return errorData;
}
}
public static String postUrl(String url, Map<String, String> params)
throws IOException {
String data = "";
for (String key : params.keySet()) {
data += "&" + URLEncoder.encode(key, "UTF-8") + "="
+ URLEncoder.encode(params.get(key), "UTF-8");
}
data = data.substring(1);
// System.out.println(data);
URL aURL = new java.net.URL(url);
HttpURLConnection aConnection = (java.net.HttpURLConnection) aURL
.openConnection();
try {
aConnection.setDoOutput(true);
aConnection.setDoInput(true);
aConnection.setRequestMethod("POST");
// aConnection.setAllowUserInteraction(false);
// POST the data
OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(
aConnection.getOutputStream());
streamToAuthorize.write(data);
streamToAuthorize.flush();
streamToAuthorize.close();
// check error
int errorCode = aConnection.getResponseCode();
if (errorCode >= 400) {
InputStream errorStream = aConnection.getErrorStream();
try {
String errorData = streamToString(errorStream);
throw new HttpException(errorCode, errorData);
} finally {
errorStream.close();
}
}
// Get the Response
InputStream resultStream = aConnection.getInputStream();
try {
String responseData = streamToString(resultStream);
return responseData;
} finally {
resultStream.close();
}
} finally {
aConnection.disconnect();
}
}
private static String streamToString(InputStream resultStream)
throws IOException {
BufferedReader aReader = new java.io.BufferedReader(
new java.io.InputStreamReader(resultStream));
StringBuffer aResponse = new StringBuffer();
String aLine = aReader.readLine();
while (aLine != null) {
aResponse.append(aLine + "\n");
aLine = aReader.readLine();
}
return aResponse.toString();
}
}
完整分享代码下载地址:http://www.zuidaima.com/share/1550463367924736.htm
转自:http://www.cnblogs.com/zhanghaoh/archive/2012/12/24/2831264.html
http://blog.csdn.net/yaerfeng/article/details/20289791
http://jucelin.com/php-get-sina-weibo-short-url.html
https://api.weibo.com/2/short_url/shorten.json?source=3818214747&url_long=http://www.baidu.com
https://api.weibo.com/2/short_url/shorten.json?source=209678993&url_long=http://www.baidu.com
public static void main(String[] args) throws Exception {
String url = "https://api.weibo.com/2/short_url/shorten.json?source=3818214747&url_long=http://www.baidu.com"; //source=209678993
URL aURL = new URL(url);
HttpURLConnection aConnection = (java.net.HttpURLConnection) aURL.openConnection();
InputStream resultStream = aConnection.getInputStream();
String responseData = streamToString(resultStream);
System.out.println(responseData);
}
private static String streamToString(InputStream resultStream)
throws IOException {
BufferedReader aReader = new java.io.BufferedReader(
new java.io.InputStreamReader(resultStream));
StringBuffer aResponse = new StringBuffer();
String aLine = aReader.readLine();
while (aLine != null) {
aResponse.append(aLine + "\n");
aLine = aReader.readLine();
}
return aResponse.toString();
}
上面的api微博和main测试程序的
输出结果json都为:
{"urls":[ {"object_type":"priMessage","result":true,"url_short":"http://t.cn/h5mwx","object_id":"2016054:230321b814888b6b8d2fee3956617f3569f79c8288","url_long":"http://www.baidu.com","type":39} ]}
附新浪微博短链接口:
http://open.weibo.com/wiki/2/short_url/shorten