简体   繁体   中英

Why does HttpWebrequest through .Net proxy fail?

I have the following code:

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

I don't understand what I do wrong?

You're not setting Proxy on your HttpWebRequest. (You're creating a WebProxy object, but not using it.) You need to add:

request.Proxy = proxyz;

before calling request.GetResponse().

You also need to fix your use of objects which implement IDisposable . Since they're created in a loop, you cannot delay this - it could be causing any amount of random damage:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM