开发者

Get current Uri when redirected in WebClient wp7

I hope that I won't start a topic that's done already but I didn't find any proper answer here nor anywere else. So here we go: I use a WebClient to download HTML Code from a webpage, then I send a new request with that WebClient and the WebPage redirects me. Now I want to now where the Site has put me.

The WebClient Class itself doesn't have any suitable properties, I already tried to rewrite the class so that I could get the Response URI but somehow it doesn't work for wp7.

So any ideas how to get the URI where my WebClient got redirected? Or any idea why the application crashes when I want to use my own class:

    public class MyWebClient : WebClient
    {
            Uri _responseUri;

            public Uri ResponseUri
            {
                get { return _responseUri; }
            }
            protected override WebResponse Ge开发者_如何学运维tWebResponse(WebRequest request, IAsyncResult result)
            {
                WebResponse response = base.GetWebResponse(request, result);
                _responseUri = response.ResponseUri;
                return response;
            }
        }
}

Thanks in advance!


HttpWebRequest is the solution here, since WebClient is a wrapper around it anyway. Something like this should work for your specific situation:

private HttpWebRequest request;
private bool flagIt = true;

public MainPage()
{
    InitializeComponent();

    request = (HttpWebRequest)WebRequest.Create("http://google.com");
    request.BeginGetResponse(new AsyncCallback(GetData), request);
}

public void GetData(IAsyncResult result)
{
    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);

    Debug.WriteLine(response.ResponseUri.ToString());

    if (flagIt)
    {
        request = (HttpWebRequest)WebRequest.Create("http://microsoft.com");
        request.BeginGetResponse(new AsyncCallback(GetData), request);
        flagIt = false;
    }
}

I am initiating the request in the main page constructor and then I am handling it in the callback. Notice how I am getting the ResponseUri - your final destination.

You don't need to handle AllowAutoRedirect if you don't want blocking the redirect and simply getting the URL, like I am doing in the snippet above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜