0

当我通过浏览器地址栏请求页面(例如: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());

请帮我!

4

3 回答 3

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

尝试这个。

于 2012-07-06T06:51:58.647 回答
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();
于 2012-07-06T14:48:56.263 回答
0

您必须检查响应标头

有关更多信息,请在此处查看http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.headers.aspx

于 2012-07-06T06:47:43.483 回答