在平常生活中,我们发表文章,网站的链接老是很长,特别是淘宝的那种链接,更是长的离谱,特别不友好,故现在开始推短链接这种应用。
原理:
其实很简单,短链接商,把你的长连接存到他的数据库中,然后根据GUID生成一个唯一标识的短链接,这个链接是请求的他们的服务器。当别人访问这个短链接的时候,短链接商就从服务器上把你的长链接读出来,然后直接跳转到你的长链接地址。
难点:
主要还是模拟POST、GET请求。其他还是比较简单的。
我做了个百度的长链接转短链接的例子。新浪和腾讯的由于需要OAuth授权,这块目前还没有接触过,不太了解,以后了解吧。
我把我做的简单的demo贴出来。
HttpRequestHelper 作用:模拟HTTP的POST GET请求的
[code lang="csharp"]
public class HttpRequestHelper
{
#region 同步通过POST方式发送数据
/// <summary>
/// 通过POST方式发送数据
/// </summary>
/// <param name="Url">url</param>
/// <param name="postDataStr">Post数据</param>
/// <param name="cookie">Cookie容器</param>
/// <returns></returns>
public static string SendDataByPost(string Url, string postDataStr, ref CookieContainer cookie)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
if (cookie.Count == 0)
{
request.CookieContainer = new CookieContainer();
cookie = request.CookieContainer;
}
else
{
request.CookieContainer = cookie;
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataStr.Length;
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
#endregion
#region 同步通过GET方式发送数据
/// <summary>
/// 通过GET方式发送数据
/// </summary>
/// <param name="Url">url</param>
/// <param name="postDataStr">GET数据</param>
/// <param name="cookie">GET容器</param>
/// <returns></returns>
public static string SendDataByGET(string Url, string postDataStr, ref CookieContainer cookie)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
if (cookie.Count == 0)
{
request.CookieContainer = new CookieContainer();
cookie = request.CookieContainer;
}
else
{
request.CookieContainer = cookie;
}
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
#endregion
}
[/code]
JsonHelper 作用:Json转换成对象
[code lang="CSharp"]
public class JsonHelper
{
/// <summary>
/// JSON格式字符转换为T类型的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonStr"></param>
/// <returns></returns>
public static T ParseFormByJson<T>(string jsonStr)
{
T obj = Activator.CreateInstance<T>();
using (System.IO.MemoryStream ms =
new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr)))
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}
[/code]
BaiduLink 请求百度返回的json数据的实体
[code lang="CSharp"]
public class BaiduLink
{
string _longurl;
/// <summary>
/// 长链接
/// </summary>
public string longurl
{
get { return _longurl; }
set { _longurl = value; }
}
string _status;
/// <summary>
/// 返回状态
/// </summary>
public string status
{
get { return _status; }
set { _status = value; }
}
string _tinyurl;
/// <summary>
/// 短链接
/// </summary>
public string tinyurl
{
get { return _tinyurl; }
set { _tinyurl = value; }
}
}
[/code]
具体实现的代码:
[code lang="CSharp"]
//参考链接:http://www.baidu.com/search/dwz.html
private void btnBaiDu_Click(object sender, EventArgs e)
{
/*
生成短网址
请求:向dwz.cn/create.php发送post请求,发送数据包括url=长网址
返回:json格式的数据
status!=0 出错,查看err_msg获得错误信息(UTF-8编码)
成功,返回生成的短网址 tinyurl字段
*/
string longlink = tbLongLink.Text.Trim();
CookieContainer cookieContainer = new CookieContainer();
string result = HttpRequestHelper.SendDataByPost("http://dwz.cn/create.php", "url=" + longlink, ref cookieContainer);
//{"longurl":"http:\/\/www.baidu.com\/s?tn=baiduhome_pg","status":0,"tinyurl":"http:\/\/dwz.cn\/2Up1h"}
BaiduLink modelResult=JsonHelper.ParseFormByJson<BaiduLink>(result);
tbShortLink.Text = modelResult.tinyurl;
}
[/code]
我把自己找的相关的资料贴出来:
1、百度长链接转短链接的API文档:http://www.baidu.com/search/dwz.html
2、新浪长链接转短链接的API文档:http://open.weibo.com/wiki/Short_url/shorten
3、腾讯长链接转短链接的API文档:http://wiki.open.t.qq.com/index.php/API%E6%96%87%E6%A1%A3/%E5%85%B6%E4%BB%96/%E7%9F%ADurl%E5%8F%98%E9%95%BFurl