我的数据库中有一个表,其中包含一些网站的 URL。我必须打开这些 URL 并验证这些页面上的一些链接。问题是某些 URL 被重定向到其他 URL。对于这样的 URL,我的逻辑是失败的。
有什么方法可以传递原始 URL 字符串并获取重定向的 URL?
示例:我正在尝试使用以下 URL:http://individual.troweprice.com/public/Retail/xStaticFiles/FormsAndLiterature/CollegeSavings/trp529Disclosure.pdf http://individual.troweprice.com/public/Retail/xStaticFiles/FormsAndLiterature/CollegeSavings/trp529Disclosure.pdf
它被重定向到这个:http://individual.troweprice.com/staticFiles/Retail/Shared/PDFs/trp529Disclosure.pdf http://individual.troweprice.com/staticFiles/Retail/Shared/PDFs/trp529Disclosure.pdf
我尝试使用以下代码:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Uris);
req.Proxy = proxy;
req.Method = "HEAD";
req.AllowAutoRedirect = false;
HttpWebResponse myResp = (HttpWebResponse)req.GetResponse();
if (myResp.StatusCode == HttpStatusCode.Redirect)
{
MessageBox.Show("redirected to:" + myResp.GetResponseHeader("Location"));
}
当我执行上面的代码时,它给了我HttpStatusCodeOk
。我很惊讶为什么它不认为这是一个重定向。如果我在 Internet Explorer 中打开该链接,它将重定向到另一个 URL 并打开 PDF 文件。
有人可以帮助我理解为什么示例 URL 无法正常工作吗?
顺便说一下,我检查了 Hotmail 的 URL(http://www.hotmail.com http://www.hotmail.com) 并且它正确返回重定向的 URL。
该函数将返回链接的最终目的地——即使有多个重定向。它不考虑基于 JavaScript 的重定向或 META 重定向。请注意,之前的解决方案没有处理绝对和相对 URL,因为 LOCATION 标头可能返回类似“/newhome”的内容,您需要与提供该响应的 URL 结合起来以识别完整的 URL 目标。
public static string GetFinalRedirect(string url)
{
if(string.IsNullOrWhiteSpace(url))
return url;
int maxRedirCount = 8; // prevent infinite loops
string newUrl = url;
do
{
HttpWebRequest req = null;
HttpWebResponse resp = null;
try
{
req = (HttpWebRequest) HttpWebRequest.Create(url);
req.Method = "HEAD";
req.AllowAutoRedirect = false;
resp = (HttpWebResponse)req.GetResponse();
switch (resp.StatusCode)
{
case HttpStatusCode.OK:
return newUrl;
case HttpStatusCode.Redirect:
case HttpStatusCode.MovedPermanently:
case HttpStatusCode.RedirectKeepVerb:
case HttpStatusCode.RedirectMethod:
newUrl = resp.Headers["Location"];
if (newUrl == null)
return url;
if (newUrl.IndexOf("://", System.StringComparison.Ordinal) == -1)
{
// Doesn't have a URL Schema, meaning it's a relative or absolute URL
Uri u = new Uri(new Uri(url), newUrl);
newUrl = u.ToString();
}
break;
default:
return newUrl;
}
url = newUrl;
}
catch (WebException)
{
// Return the last known good URL
return newUrl;
}
catch (Exception ex)
{
return null;
}
finally
{
if (resp != null)
resp.Close();
}
} while (maxRedirCount-- > 0);
return newUrl;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)