【发布时间】:2013-11-20 09:13:11
【问题描述】:
我正在做一个使用代理获取网站 HTML 代码的项目。
现在,我遇到的问题是我想在连接代理时使用用户名密码身份验证而不是 IP 身份验证。
我编写了一个示例代码并使用Snippy 运行它。有效。然后我将相同的代码复制到 Visual Studio .NET 4.5 项目中,但失败并出现错误:An existing connection was forcibly closed by the remote host 尝试获取响应时。
代码如下:
WebProxy[] proxies = { new WebProxy("ip", port) };
proxies[0].Credentials = new NetworkCredential { UserName = "username", Password = "password" };
string url = "https://www.google.com/search?q=s&num=50";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Proxy = proxies[0];
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
using (StreamReader response_stream = new StreamReader(res.GetResponseStream())
{
string html = response_stream.ReadToEnd();
Console.WriteLine(html);
}
}
我尝试了不同的变体。当我切换到 IP 授权时,添加我的并注释掉 NetworkCredentials 分配,代码在 Snippy 和 Visual Studio 中都能完美运行。
但为什么在使用 NetworkCredentials 时会失败?
【问题讨论】:
标签: c# .net visual-studio-2012 proxy httpwebresponse