我正在尝试创建一个使用.NET Framework消费RSS数据的应用程序。 RSS站点需要用户名和密码才能开始。 并且我在我的工作场所运行此应用程序,这需要NTLM身份验证才能连接到互联网。
以下是我尝试使用的代码
NetworkCredential nc = new NetworkCredential("SITEUSERNAME", "SITEPASSWORD");
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(RSSFeed), "Basic", nc);
cache.Add(new Uri(RSSFeed), "Ntlm", new NetworkCredential("USERNAME","PASSWORD","DOAMIN"));
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RSSFeed);
myHttpWebRequest.Proxy.Credentials = cache;
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
我得到407错误,如果我只是使用CredentialCache.DefaultNetworkCredentials,我得到401错误。
答案 0 :(得分:3)
使用以下代码
解决了这个问题 string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("UserName" + ":" + "Password"));
StringBuilder outputData = new StringBuilder();
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RSSFeed);
myHttpWebRequest.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
myHttpWebRequest.Headers.Add("Authorization", "Basic " + credentials);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream streamResponse = myHttpWebResponse.GetResponseStream();
答案 1 :(得分:1)
如果此代码有效,那么上面的原始代码是错误的。你应该设置
request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
和
NetworkCredential nc = new NetworkCredential("SITEUSERNAME", "SITEPASSWORD");
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(RSSFeed), "Basic", nc);
cache.Add(new Uri(RSSFeed), "Ntlm", new NetworkCredential("USERNAME","PASSWORD","DOAMIN"));
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RSSFeed);
myHttpWebRequest.Credentials = cache;
换句话说,您已经交换了代理和目标服务器的凭据。