C# 中的代理基本身份验证:HTTP 407 错误 [英] Proxy Basic Authentication in C#: HTTP 407 error

查看:34
本文介绍了C# 中的代理基本身份验证:HTTP 407 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用需要身份验证的代理,即在浏览器中,如果我尝试打开一个页面,它会立即要求提供凭据.我在我的程序中提供了相同的凭据,但它因 HTTP 407 错误而失败.

I am working with a proxy that requires authentication, i.e., in a browser if I try to open a page it will immediately ask for credentials. I supplied same credentials in my program but it fails with HTTP 407 error.

这是我的代码:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

IWebProxy proxy = WebRequest.GetSystemWebProxy();
CredentialCache cc = new CredentialCache();
NetworkCredential nc = new NetworkCredential();

nc.UserName = "userName";
nc.Password = "password";
nc.Domain = "mydomain";
cc.Add("http://20.154.23.100", 8888, "Basic", nc);
proxy.Credentials = cc;
//proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Proxy = proxy;
request.Proxy.Credentials = cc;
request.Credentials = cc;
request.PreAuthenticate = true;

我已经尝试了所有可能的方法,但似乎我遗漏了一些东西.是不是像,我必须提出两个要求?首先没有凭据,一旦我从服务器听到需要凭据的消息,就用凭据发出相同的请求?

I have tried every possible thing but seem like I am missing something. Is it something like, I have to make two requests? First with out credentials and once I hear back from server about need for credentials, make same request with credentials?

推荐答案

这里是使用代理和凭据的正确方法..

here is the correct way of using proxy along with creds..

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

IWebProxy proxy = request.Proxy;                    
if (proxy != null)
{
    Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
}
else
{
    Console.WriteLine("Proxy is null; no proxy will be used");
}

WebProxy myProxy = new WebProxy();
Uri newUri = new Uri("http://20.154.23.100:8888");
// Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
myProxy.Address = newUri;
// Create a NetworkCredential object and associate it with the 
// Proxy property of request object.
myProxy.Credentials = new NetworkCredential("userName", "password");
request.Proxy = myProxy;

谢谢大家的帮助... :)

Thanks everyone for help... :)

这篇关于C# 中的代理基本身份验证:HTTP 407 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆