C#代码,用于在通过Web请求URL时从需要用户名和密码的URL获得自动响应

时间:2012-07-06 06:46:26

标签: c#

当我通过浏览器地址栏请求页面(例如:http://mysite.com/mypage)时,它会提示我一条消息[如:需要验证:服务器http://mysite.com/mypage:80需要用户名和密码...]。当我提供用户名和密码时,它会显示对浏览器的响应。否则它说:用户未经授权。

我想使用C#代码自动执行此过程,以便我可以在代码中获取响应。因为它提示用户名和密码所以我无法通过HttpWebRequest / Response获得响应。

我尝试过以下代码块:

       HttpWebRequest webRequest = WebRequest.Create(myUrl) as HttpWebRequest;

       webRequest.Proxy = WebRequest.DefaultWebProxy;

        webRequest.Credentials = new NetworkCredential(userName, password);
        webRequest.Proxy.Credentials = new NetworkCredential(userName, password);

        HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
        System.IO.Stream stream = response.GetResponseStream();

        System.IO.StreamReader sReader = new System.IO.StreamReader(stream);
        Console.WriteLine(sReader.ReadToEnd());

请帮助我!

3 个答案:

答案 0 :(得分:0)

您必须检查响应标题

了解更多信息,请点击此处http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.headers.aspx

答案 1 :(得分:0)

string formParams = string.Format("user={0}&password={1}&switch=Log+In", username, password);
            WebRequest req = WebRequest.Create(Login_Page_URL);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";
            req.Proxy.Credentials = CredentialCache.DefaultCredentials;
            byte[] bytes = Encoding.ASCII.GetBytes(formParams);
            req.ContentLength = bytes.Length;
            using (Stream os = req.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }
            resp = req.GetResponse();
            cookieHeader = resp.Headers["Set-cookie"];
            resp.Close();

// to view the page behing login page

            WebRequest getRequest = WebRequest.Create(Page_Behing_login_Page_URL);
            getRequest.Headers.Add("Cookie", cookieheader);
            WebResponse getResponse = getRequest.GetResponse();
            using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
            {
                pageSource = sr.ReadToEnd();
            }

试试这个。

答案 2 :(得分:0)

最后我找到了解决方案。我请求的站点需要基本的IIS身份验证。我用以下方式解决了这个问题:

        WebRequest webRequest = WebRequest.Create(finalUrl);
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
        CredentialCache credentialCache = new CredentialCache();
        credentialCache.Add(new System.Uri(finalUrl), "Basic", new NetworkCredential(userName, password));

        webRequest.Credentials = credentialCache;
        webRequest.PreAuthenticate = true;

        HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

        System.IO.Stream stream = response.GetResponseStream();

        System.IO.StreamReader sReader = new System.IO.StreamReader(stream);
        pageSource = sReader.ReadToEnd();