为什么通过.Net代理的HttpWebrequest失败?

时间:2010-01-08 23:01:10

标签: c# proxy httpwebrequest

我有以下代码:

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);
  }

我不明白我做错了什么?

2 个答案:

答案 0 :(得分:1)

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

request.Proxy = proxyz;

在调用request.GetResponse()。

之前

答案 1 :(得分:1)

您还需要修复对实现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();
        }
    }