无法在C#中连接到具有401未授权错误的URL

时间:2014-11-19 00:10:33

标签: c# url webclient http-status-code-401

我希望从

获取网页内容
http://12.18.60.199:81 

我正在使用我的公司网络,如果我使用的是Internet Explorer,它会提示输入用户名和密码,我输入该信息并获取该页面的内容。我需要在C#中这样做,但过去几个小时没有运气:

Uri requestUri = null;
Uri.TryCreate("http://12.18.60.199:81", UriKind.Absolute, out requestUri);

NetworkCredential nc = new NetworkCredential(@"username", @"password", "domain");
CredentialCache cache = new CredentialCache();
cache.Add(requestUri, "Basic", nc); //also tried "Anonymous", "Basic", "Digest",  "Dpa", 
                                 //"External", "Kerberos", "Msn", "Negotiate", "Ntlm", "Sicily" 

using (WebClient client = new WebClient())
{
   client.Credentials = cache;
   using (Stream stream = client.OpenRead("http://12.18.60.199:81"))
   using (StreamReader reader = new StreamReader(stream))
   {
      //stuff
   }
}

继续获取401未经授权,无效的凭据,帮助!

如果我将上述地址替换为http://google.com,它就可以正常工作,因此代码可以运行...用户名和密码已经过测试,可以在broswer中使用

2 个答案:

答案 0 :(得分:0)

如果您通过代理服务器进行连接,请尝试在代理中添加并传递凭据。例如:

// Prepare web request...
HttpWebRequest myRequest =
   (HttpWebRequest)WebRequest.Create("http://www.test.com");
// proxy details
myRequest.Proxy = new WebProxy("http://10.0.0.1", true);
myRequest.Proxy.Credentials = new NetworkCredential("test", "password", "domain");

答案 1 :(得分:0)

我遇到了同样的问题,并找到了解决方法来添加授权请求标头。我用过fiddler来获得base64。从来没有找到适当的解决方案,因为你们都知道临时解决方案在世界上是持久的:)

service.Url = "http://127.0.0.1/";
service.SetRequestHeader("Authorization", "Basic dW8sX3NvYXB6SjRma2pzdXZqNDg5ZA==");            
service.PreAuthenticate = true;