随着微博的盛行,推出短地址服务的网站是越来越多了,如最近新浪重金买下的t.cn。当用户在浏览器中访问短地址时,服务器端一般会通过返回302状态使用户浏览器跳转到正确页面。而在302响应的header中会有个[Location]的键值,它保存着要跳转的真正url。我们只要模拟请求短地址再获取header中的Location内容,就能拿到正确的页面url。
代码如下,唯一需要注意的是,一定要设HttpWebRequest的AllowAutoRedirect属性为false,要不返回的response会是跳转后页面的。
/// <summary>
/// 还原短地址
/// </summary>
public static string ExpandShortUrl(string shortUrl)
{
string nativeUrl = null;
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(shortUrl);
req.AllowAutoRedirect = false; // 禁止自动跳转
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
if (response.StatusCode == HttpStatusCode.Found)
nativeUrl = response.Headers["Location"];
}
catch (Exception ex)
{
nativeUrl = null;
}
return nativeUrl;
}
/// 还原短地址
/// </summary>
public static string ExpandShortUrl(string shortUrl)
{
string nativeUrl = null;
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(shortUrl);
req.AllowAutoRedirect = false; // 禁止自动跳转
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
if (response.StatusCode == HttpStatusCode.Found)
nativeUrl = response.Headers["Location"];
}
catch (Exception ex)
{
nativeUrl = null;
}
return nativeUrl;
}