3
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) 需要代理身份验证。

我怎样才能解决这个问题?

4

1 回答 1

2

您当前未在代理中使用凭据。这是一个改编自 MSDN 的示例,说明如何使用您的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>

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

于 2011-11-22T07:36:48.373 回答