package com.risenb.latestTools;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @author pc
* 生成短网址并返回
* Java调用百度API生成短网址
*/
public class GenerateShortUrlUtil {
public static Logger logger = LoggerFactory.getLogger(GenerateShortUrlUtil.class);
public static HttpClient client;
static {
client = HttpClients.createDefault();
}
/**
* 测试生成端连接
* @param args
*/
public static void main(String []args){
generateShortUrl("https://blog.csdn.net/xuforeverlove");
}
/**
* 生成短链接信息
*/
public static String generateShortUrl(String url) {
String shortUrl = "";
try {
//httpPost请求
HttpPost httpost = new HttpPost("http://dwz.cn/create.php");
List<NameValuePair> params = new ArrayList<NameValuePair>();
//url长连接地址
params.add(new BasicNameValuePair("url", url));
httpost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse response = client.execute(httpost);
String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
//把字符串转为对象
JSONObject object = JSONObject.parseObject(jsonStr.replace("\\", ""));
//JSONObject parseObject = JSON.parseObject(jsonStr.replace("\\", ""));
//短连接地址
shortUrl = object.get("tinyurl").toString();
System.out.println(object.get("tinyurl"));
//System.out.println(parseObject.get("tinyurl"));
/*{"tinyurl":"http://dwz.cn/7KKGUg","status":0,"longurl":"http://blog.csdn.net/xuforeverlove","err_msg":""}
System.out.println(jsonStr.replace("\\", ""));*/
} catch (Exception e) {
logger.info("调取百度API错误!");
}
return shortUrl;
}
}
百度api返回短地址: http://dwz.cn/7KKGUg
============================================================================
附上生成短链接随机码方法:
package com.risenb.latestTools;
import java.util.Random;
import org.apache.commons.codec.digest.DigestUtils;
/**
* @author pc
* 长链变短链
*/
public class LongToBrokenChain {
public static void main(String[] args) {
// 长连接
String longUrl = "http://www.hufkodfsjdfkdjfr.com/loginController/homepage.json";
// 转换成的短链接后6位码
String[] shortCodeArray = shortUrl(longUrl);
for (int i = 0; i < shortCodeArray.length; i++) {
System.out.println(shortCodeArray[i]);// 任意一个都可以作为短链接码
}
shortUrl2();
}
/**
* 生成6位的随机码
* @param url
* @return
* 原理 当我们生成短链接之后,只需要在表中(数据库或者NoSql )存储原始链接与短链接的映射关系即可。
* 当我们访问短链接时,只需要从映射关系中找到原始链接,即可跳转到原始链接。
*/
public static String[] shortUrl(String url) {
// 可以自定义生成 MD5 加密字符传前的混合 KEY
String key = "131400";
// 要使用生成 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 = DigestUtils.md5Hex(key + url);
String hex = sMD5EncryptResult;
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;
}
/**
* 生成7位的短连接
*/
public static void shortUrl2() {
/** 网址长度为7 */
final int LENGTH = 7;
/** 每右移5位,生成一个字符 */
final int PER_VARCHAR = 5;
char[] c = new char[] { '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',
'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' };
// 2的35次方,每五位一个字符,可生成7个字符
// 11111111111111111111111111111111111
long long16 = (long) Math.pow(2, PER_VARCHAR * LENGTH) - 1;
// TODO md5-32位实现
String a = "F7491217829C527F3E81C1FCBB26C9F9";
// 生成随机数,使之成为35长度
// 每8字符=32位,加3位=111
Random random = new Random();
int nextInt = random.nextInt(8);
int subIndexStart = 0;
while (subIndexStart < a.length()) {
StringBuffer sb = new StringBuffer();
// 8位一组,使用16进行转换,可转换成 4*8=32长度二进制
String substring = a.substring(subIndexStart, subIndexStart += 8);
long parseLong = Long.parseLong(nextInt + substring, 16);
long x = long16 & parseLong;
for (int j = 0; j < LENGTH; j++) {
long x2 = (c.length - 1) & x;
sb.append(c[(int) x2]);
x = x >> PER_VARCHAR;
}
System.out.println(sb);
}
}
}