代理验证错误

时间:2011-11-22 07:32:14

标签: c# .net network-programming proxy-authentication

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.example.com");
NetworkCredential nc = new NetworkCredential("myname", "mypass");
WebProxy myproxy = new WebProxy("192.168.1.1:8080", false);
myHttpWebRequest.Proxy = myproxy;
myHttpWebRequest.Proxy = WebRequest.DefaultWebProxy;
myHttpWebRequest.Method = "GET";

HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
MessageBox.Show("Ok");

我正在使用此代码连接网站(C#.net桌面应用程序)。但我收到此错误消息:

  

远程服务器返回错误:(407)需要代理验证。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您目前没有在代理中使用凭据。这是一个example adapted from MSDN of how to use your NetworkCredential

class Downloader
{
    static void Main(string[] args)
    {
        NetworkCredential nc = new NetworkCredential(args[0], args[1]);
        WebProxy proxy = new WebProxy(args[2], false);
        proxy.Credentials = nc;

        WebRequest request = new WebRequest(args[3]);
        request.Proxy = proxy;
        using (WebResponse response = request.GetResponse())
        {
            Console.WriteLine(
                @"{0} - {1} bytes",
                response.ContentType,
                response.ContentLength);
        }
    }
}

当我编译并运行这个完整的例子时:

C:\cs>csc proxy.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.


C:\cs>proxy user pass http://proxy:80 http://www.google.com
text/html; charset=ISO-8859-1 - 31398 bytes

C:\cs>

当然我使用我的实际用户/通行证和代理作为我的工作帐户。