public class LibShortUrlHelper
{
private static Hashtable _longShortURLTable;
/// <summary>缓存短网址</summary>
protected static Hashtable LongShortURLTable
{
get
{
if (_longShortURLTable == null)
_longShortURLTable = new Hashtable();
return _longShortURLTable;
}
}
static LibShortUrlHelper()
{
LongShortURLTable.Clear();
}
/// <summary>获取新浪短域名</summary>
/// <param name="url">原始地址</param>
/// <returns></returns>
public static bool TrySinaShortUrl(string url, out string shortURL)
{
bool result = false;
shortURL = "";
string html = "";
try
{
bool hasFound = false;
string url_low = url.ToLower();
lock (LibShortUrlHelper.LongShortURLTable)
{
if(LibShortUrlHelper.LongShortURLTable.ContainsKey(url_low))
{
shortURL = LibSysUtils.ToString(LibShortUrlHelper.LongShortURLTable[url_low]);
hasFound = true;
}
}
if (hasFound)
{
result = true;
}
else
{
if (NetworkUtils.GetWebPageContent("http://api.t.sina.com.cn/short_url/shorten.json?source=1681459862&url_long=" + LibSysUtils.UrlEncode(url), Encoding.UTF8, out html))
{
html = html.Replace("[", "").Replace("]", "");
ShortUrl rspData = (ShortUrl)LibSerializerControl.DeserializeFromString<LibJsonSerializer>(html, typeof(ShortUrl));
shortURL = LibSysUtils.ToString(rspData.url_short);
result = !String.IsNullOrEmpty(shortURL);
if(result)
{
lock (LibShortUrlHelper.LongShortURLTable)
{
if (!LibShortUrlHelper.LongShortURLTable.ContainsKey(url_low))
{
LibShortUrlHelper.LongShortURLTable.Add(url_low, shortURL);
}
}
}
}
}
}
catch(System.Exception ex)
{
LibSysUtils.AppendLog(ex);
}
return result;
}
/// <summary>获取Yep.it短域名</summary>
/// <param name="url">原始地址</param>
/// <returns></returns>
public static bool TryYepShortUrl(string url, out string shortURL)
{
bool result = false;
shortURL = "";
string html = "";
try
{
bool hasFound = false;
string url_low = url.ToLower();
lock (LibShortUrlHelper.LongShortURLTable)
{
if (LibShortUrlHelper.LongShortURLTable.ContainsKey(url_low))
{
shortURL = LibSysUtils.ToString(LibShortUrlHelper.LongShortURLTable[url_low]);
hasFound = true;
}
}
if (hasFound)
{
result = true;
}
else
{
if (NetworkUtils.GetWebPageContent("http://yep.it/api.php?url=" + LibSysUtils.UrlEncode(url), Encoding.UTF8, out html))
{
shortURL = LibSysUtils.ToString(html).Trim();
result = !String.IsNullOrEmpty(shortURL);
if (result)
{
lock (LibShortUrlHelper.LongShortURLTable)
{
if (!LibShortUrlHelper.LongShortURLTable.ContainsKey(url_low))
{
LibShortUrlHelper.LongShortURLTable.Add(url_low, shortURL);
}
}
}
}
}
}
catch (System.Exception ex)
{
LibSysUtils.AppendLog(ex);
}
return result;
}
}
[Serializable]
public class ShortUrl
{
/// <summary>
/// 短域名
/// </summary>
public virtual string url_short { get; set; }
/// <summary>
/// 长域名
/// </summary>
public virtual string url_long { get; set; }
/// <summary>
/// 类型
/// </summary>
public virtual int type { get; set; }
}
【代码片段】生成短网址
最新推荐文章于 2024-06-05 10:52:59 发布