HttpWebResponse重定向到错误页面

时间:2014-04-23 15:14:09

标签: c# asp.net httpwebresponse

当我通过浏览器加载http://support.microsoft.com/common/survey.aspx?scid=sw%3ben%3b3547&showpage=1时,我正在访问正确的页面,但是当我执行以下操作时,HttpWebResponse将返回不存在的其他uri。请帮助!!!

private string[] getTitleNewUrl()
{
    string[] titleNewUrl = new string[2];
    var navigatedUrl = string.Empty;

    string title = string.Empty;
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://support.microsoft.com/common/survey.aspx?scid=sw%3ben%3b3547&showpage=1");
        request.Credentials = System.Net.CredentialCache.DefaultCredentials;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            navigatedUrl = response.ResponseUri.ToString(); **//this returns [http://support.microsoft.com/default.aspx?scid=gp;en-us;fmserror][1]**

            StreamReader sr = new StreamReader(response.GetResponseStream());
            var htmlSource = sr.ReadToEnd();

            Match m = Regex.Match(htmlSource, @"<title>\s*(.+?)\s*</title>");
            if (m.Success)
            {
                title = m.Groups[1].Value;
            }

            titleNewUrl[0] = title;
            titleNewUrl[1] = navigatedUrl;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Invalid URL: " + navigatedUrl + " Error: " + ex.Message);
    }

    return titleNewUrl;
}

1 个答案:

答案 0 :(得分:0)

您必须使用他们可以使用的一些用户代理,例如:

request.UserAgent = "Mozilla";