本文介绍了在 C# 中使用 WebClient 有没有办法在重定向后获取站点的 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 WebClient 类我可以很容易地获得网站的标题:

Using the WebClient class I can get the title of a website easily enough:

WebClient x = new WebClient();    
string source = x.DownloadString(s);
string title = Regex.Match(source, 
    @"<title[^>]*>s*(?<Title>[sS]*?)</title>",
    RegexOptions.IgnoreCase).Groups["Title"].Value;

我想存储 URL 和页面标题.但是,当点击以下链接时:

I want to store the URL and the page title. However when following a link such as:

http://tinyurl.com/dbysxp

我显然想要获得重定向到的 URL.

I'm clearly going to want to get the Url I'm redirected to.

问题

有没有办法使用 WebClient 类来做到这一点?

Is there a way to do this using the WebClient class?

我将如何使用 HttpResponseHttpRequest 来做到这一点?

How would I do it using HttpResponse and HttpRequest?

推荐答案

如果我理解了这个问题,这比人们说的要容易得多——如果你想让 WebClient 完成请求的所有细节(包括重定向)),然后在最后获得实际响应URI,您可以像这样子类WebClient:

If I understand the question, it's much easier than people are saying - if you want to let WebClient do all the nuts and bolts of the request (including the redirection), but then get the actual response URI at the end, you can subclass WebClient like this:

class MyWebClient : WebClient
{
    Uri _responseUri;

    public Uri ResponseUri
    {
        get { return _responseUri; }
    }

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

只要在您会使用 WebClient 的任何地方使用 MyWebClient.在您完成您需要执行的任何 WebClient 调用之后,您就可以使用 ResponseUri 来获取实际的重定向 URI.如果您使用的是异步内容,您还需要为 GetWebResponse(WebRequest request, IAsyncResult result) 添加类似的覆盖.

Just use MyWebClient everywhere you would have used WebClient. After you've made whatever WebClient call you needed to do, then you can just use ResponseUri to get the actual redirected URI. You'd need to add a similar override for GetWebResponse(WebRequest request, IAsyncResult result) too, if you were using the async stuff.

这篇关于在 C# 中使用 WebClient 有没有办法在重定向后获取站点的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 02:40