【问题标题】:Why does HttpWebrequest through .Net proxy fail?为什么通过 .Net 代理的 HttpWebrequest 失败?
【发布时间】:2010-01-08 23:01:10
【问题描述】:

我有以下代码:

int repeat = 1;
int proxyIndex = 1;
if (listBox1.Items.Count == proxyIndex) //If we're at the end of the proxy list
{
  proxyIndex = 0; //Make the selected item the first item in the list
}
try
{
  int i = 0;
  while (i < listBox1.Items.Count)
  {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(textBox1.Text);
    string proxy = listBox1.Items[i].ToString();
    string[] proxyArray = proxy.Split(':');
    WebProxy proxyz = new WebProxy(proxyArray[0], int.Parse(proxyArray[1]));
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());
    string str = reader.ReadToEnd();
    Thread.Sleep(100);
    {
      repeat++;
      continue;
    }
  }
  catch (Exception ex) //Incase some exception happens
  {
    listBox2.Items.Add("Error:" + ex.Message);
  }

我不明白我做错了什么?

【问题讨论】:

  • 如果你告诉我们它是做什么或不做什么会有所帮助
  • 基本上,程序的特点是;用户可以将代理列表加载到列表框中,然后它将浏览文本框中指定的链接;移动到下一个代理浏览页面然后继续等等。它不是在浏览页面..
  • Lawrence,我尝试重新格式化您的代码(基本上是尝试使缩进保持一致以使其更具可读性),但据我所知,它有问题 - try 和 catch 块似乎不匹配。您能否仔细检查一下您是否拥有实际程序中的所有大括号等?
  • 是的,所有的大括号都匹配..我不知道出了什么问题:(
  • OBTW,没有 C# 代理之类的东西。您的意思是 .NET 代理。

标签: c# proxy httpwebrequest


【解决方案1】:

您没有在 HttpWebRequest 上设置代理。 (您正在创建一个 WebProxy 对象,但没有使用它。)您需要添加:

request.Proxy = proxyz;

在调用 request.GetResponse() 之前。

【讨论】:

    【解决方案2】:

    您还需要修正对实现IDisposable 的对象的使用。由于它们是在循环中创建的,因此您不能延迟它 - 它可能会造成任意数量的随机损坏:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        string[] proxyArray = proxyHostAndPort.Split(':');
        WebProxy proxyz = new WebProxy(proxyArray[0], int.Parse(proxyArray[1]));
        request.Proxy = proxyz;
        using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string str = reader.ReadToEnd();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 2020-01-07
      • 2020-03-12
      • 1970-01-01
      相关资源
      最近更新 更多