2010-01-08 49 views
0

我有以下代码:为什么通过.Net代理的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); 
    } 

我不明白我做错了什么?

+3

如果你告诉我们什么是或不是做 – 2010-01-08 23:01:45

+0

基本上,功能这将有助于的程序是;用户可以将代理列表加载到列表框中,然后它将浏览在文本框中指定的链接;移动到下一个代理浏览页面,然后移动等.. 它不是浏览页面.. – Lawrence 2010-01-08 23:10:02

+0

劳伦斯,我试图重新格式化您的代码(基本上试图让缩进一致,使其更可读),但从我可以告诉它有什么问题 - try和catch块似乎不匹配。你能仔细检查你的实际程序中是否有所有大括号等吗? – itowlson 2010-01-08 23:17:37

回答

1

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

request.Proxy = proxyz; 

调用request.GetResponse前()。

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