求短网址计算~

stonepeter 2011-01-04 10:26:29
听说GOOGLE和BAIDU都提供了短网址服务,请有人在C#代码里调用过这样的服务在程序里计算并显示短网址么?
求算法。
谢谢~
...全文
181 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
-小蕾- 2011-01-04
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 slimboy123 的回复:]
http://blog.csdn.net/slimboy123/archive/2010/08/03/5786721.aspx
[/Quote]
不错。
stoneallen 2011-01-04
  • 打赏
  • 举报
回复
学习下
stonepeter 2011-01-04
  • 打赏
  • 举报
回复

private static string GetShortenUrl(string longUrl)
{
const string urlformatter = "http://api.bit.ly/v3/shorten?login=stonepeter&apiKey=R_602a98ce2ef8feed660747065c1d7bae&longUrl={0}&format=xml";
var bitlyRequest = string.Format(urlformatter, UrlEncode(longUrl));
var xmlresult = WebRequest(Method.GET, bitlyRequest, null);
var xml = new XmlDocument();
xml.LoadXml(xmlresult);
string shortenUrl = xml.GetElementsByTagName("url")[0].InnerText;

return shortenUrl;
}

/// <summary>
/// Replace all Urls with shorten one
/// </summary>
/// <param name="orginal">The orginal text string</param>
/// <returns>If there are urls replace it with bit.ly shorten name</returns>
public static string ReplaceUrlWithShorten(string orginal)
{
Regex urlRegex = new Regex(@"http://[^\s]*");
MatchCollection matches = urlRegex.Matches(orginal);
string result = orginal;

foreach (Match match in matches)
{
string matchvalue = match.Value;
result = result.Replace(matchvalue, GetShortenUrl(matchvalue));
}
return result;
}
stonepeter 2011-01-04
  • 打赏
  • 举报
回复
以下C#代码示例了如何用bit.ly网站提供的API服务获得URL短地址
private static string GetShortenUrl(string longUrl)
{
const string urlformatter = "http://api.bit.ly/v3/shorten?login=stonepeter&apiKey=R_602a98ce2ef8feed660747065c1d7bae&longUrl={0}&format=xml";
var bitlyRequest = string.Format(urlformatter, UrlEncode(longUrl));
var xmlresult = WebRequest(Method.GET, bitlyRequest, null);
var xml = new XmlDocument();
xml.LoadXml(xmlresult);
string shortenUrl = xml.GetElementsByTagName("url")[0].InnerText;

return shortenUrl;
}

/// <summary>
/// Replace all Urls with shorten one
/// </summary>
/// <param name="orginal">The orginal text string</param>
/// <returns>If there are urls replace it with bit.ly shorten name</returns>
public static string ReplaceUrlWithShorten(string orginal)
{
Regex urlRegex = new Regex(@"http://[^\s]*");
MatchCollection matches = urlRegex.Matches(orginal);
string result = orginal;

foreach (Match match in matches)
{
string matchvalue = match.Value;
result = result.Replace(matchvalue, GetShortenUrl(matchvalue));
}
return result;
}
stonepeter 2011-01-04
  • 打赏
  • 举报
回复
不知道最近是为何。来CSDN总是得不到自己的答案了。CSDN论坛一定出了某些问题。

7,774

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧