在C#中使用Web客户端,有没有办法被重定向后得到一个网站的网址? [英] Using WebClient in C# is there a way to get the URL of a site after being redirected?

查看:159
本文介绍了在C#中使用Web客户端,有没有办法被重定向后得到一个网站的网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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\b[^>]*\>\s*(?<Title>[\s\S]*?)\</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.

问题

有没有办法使用 Web客户端类来做到这一点?

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

我将如何做到这一点使用的Htt presponse 的Htt prequest

How would I do it using HttpResponse and HttpRequest?

推荐答案

如果我理解这个问题,它更容易比人们都在说 - 如果你想要让WebClient的要求去做所有的螺母和螺栓(包括重定向),但后来获得的实际的响应URI的尽头,你也可以继承Web客户端是这样的:

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;
    }
}

只需使用MyWebClient无处不在,你会使用Web客户端。当你做你需要做什么WebClient的调用,那么你可以只用ResponseUri得到实际的重定向URI。 你需要添加一个类似的倍率GetWebResponse(WebRequest的要求,IAsyncResult的结果)也一样,如果你使用了异步的东西。

这篇关于在C#中使用Web客户端,有没有办法被重定向后得到一个网站的网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆