C# 无法连接到C中的url,出现错误

C# 无法连接到C中的url,出现错误,c#,url,webclient,http-status-code-401,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

我想从中获取页面内容

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个未经授权的无效凭据,帮助


如果我用替换上面的地址,它会工作,所以代码工作。。。用户名和密码已经过测试,可以在broswer中工作

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

// 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");

我也遇到了同样的问题,并找到了添加授权请求头的解决方法。我用提琴手打了那个基础。从未找到合适的解决方案,正如大家所知,临时解决方案在世界各地都是持久的:

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

是否通过代理服务器运行?确保服务器使用基本身份验证?试试digest。我对这些东西不是很在行,我相信我在连接到internet时使用了我公司的代理服务器,因为某些站点被阻止。该死的,我尝试了匿名、基本、digest、Dpa、外部、Kerberos、Msn、协商、Ntlm、西西里同样的401错误,我也无法连接到它…:嗨,j.v,这看起来很有趣,你能粘贴完整的代码示例吗?差不多就是这样。我将其用于不同的目的,用于web服务授权。这只是给你的暗示。祝你好运