Get current Uri when redirected in WebClient wp7

三世轮回 提交于 2019-12-07 17:45:29

问题


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 GetWebResponse(WebRequest request, IAsyncResult result)
            {
                WebResponse response = base.GetWebResponse(request, result);
                _responseUri = response.ResponseUri;
                return response;
            }
        }
}

Thanks in advance!


回答1:


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.




回答2:


Use HttpWebRequest instead of WebClient and set AllowAutoRedirect to false.

Also this can be helpful Getting the location from a WebClient on a HTTP 302 Redirect?



来源:https://stackoverflow.com/questions/6900024/get-current-uri-when-redirected-in-webclient-wp7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!