如何通过WebClient获得Redirect之后的地址?

Unlike its brother HttpWebRequest, the WebClient class automatically follows redirects, but if you need to get the "final" url, you'll need to "wrap" your WebClient in a class that derives from System.Net.WebClient. Here's an example:

using System;
using System.Net; 

public class MyWebClient : WebClient
{
    Uri _responseUri; 

    public Uri ResponseUri
    {
        get { return _responseUri; }
    } 

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = null;
        try
        {
            response = base.GetWebResponse(request);
            _responseUri = response.ResponseUri;
        }
        catch
        {
        }
        return response;
    }
} 

By overriding the GetWebResponse method, we can populate a ResponseUri property with the final target of any 302 rediirects. Redirects are very common in all kinds of websites as they allow the owner to count hits, and log information before sending you on your merry way to the target.

Here's some sample code that goes through a whole list of integer "Redirect Ids", assembles the page title and final url, and saves these to a delimited text file that can be read later:

static string urlbase="http://sitewithredirect.com/Redirect.aspx?id=";

static void ProcessUrls()
{
    string regex = @"(?<=<title.*>)([\s\S]*)(?=</title>)";
    for (int i =1; i < 4000; i++)
    {
        string item = i.ToString();
        string url = urlbase + item;
        string content = null;
        string targetUrl = null;
        string title = null;
        MyWebClient w = new MyWebClient();
        try
        {
            content = w.DownloadString(url);
            targetUrl = w.ResponseUri.ToString();
            Regex rex = new Regex(regex, RegexOptions.IgnoreCase);
            title = rex.Match(content).Value.Trim();
            System.Diagnostics.Debug.WriteLine(targetUrl);
        }
        catch
        {
            System.Diagnostics.Debug.WriteLine(item);
        } 

        w.Dispose(); 

        if (targetUrl != null && title != null )
        {
            System.IO.File.AppendAllText(@"urls.txt", targetUrl + "|" + title + "\r\n");
        }
    } 

} 

原文地址:http://www.eggheadcafe.com/tutorials/aspnet/70511872-c3aa-4e92-a7d7-dd4b09881af5/make-the-webclient-class-follow-redirects-and-get-target-url.aspx

转载于:https://www.cnblogs.com/cppfans/articles/1942351.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值