2010-01-08 50 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(); 
     } 
    }