2011-06-30 31 views
4

我試圖通過SOCKS代理的列表進行排序,並找出哪些有一個連接並讀取小於1000毫秒的時間,這裏是我的代碼如何使用URLConnection的超時

for(Proxy p : proxies) { 
      try { 
      URLConnection testConnection = testUrl.openConnection(p); 
      testConnection.setConnectTimeout(TIMEOUT_VALUE); 
      testConnection.setReadTimeout(TIMEOUT_VALUE); 
      success.add(p); 
      } catch(SocketTimeoutException ste) { 
       System.out.println("Proxy " + p.address().toString() + " timed out."); 
      } 
     } 

但每單其中一人通過測試,即使當我做TIMEOUT_VALUE = 1;我做錯了什麼?謝謝你的幫助。

+0

你能加入這行,看看它返回值? 'testConnection.getConnectTimeout()' – CoolBeans

+0

我的意思是在設置超時值後添加。 – CoolBeans

+0

@CoolBeans它只是打印1000,就像它應該的。 – Austin

回答

10

我假設你的問題是你沒有閱讀任何連接。如果我將TIMEOUT_VALUE設置得太低,我會得到一個例外。無論我是閱讀所有答案還是隻閱讀一行都不會影響結果時間,我想這是因爲我在一個數據包中得到了完整答案。

下面是我用的測量(無代理):

int TIMEOUT_VALUE = 1000; 
    try { 
     URL testUrl = new URL("http://google.com"); 
     StringBuilder answer = new StringBuilder(100000); 

     long start = System.nanoTime(); 

     URLConnection testConnection = testUrl.openConnection(); 
     testConnection.setConnectTimeout(TIMEOUT_VALUE); 
     testConnection.setReadTimeout(TIMEOUT_VALUE); 
     BufferedReader in = new BufferedReader(new InputStreamReader(testConnection.getInputStream())); 
     String inputLine; 

     while ((inputLine = in.readLine()) != null) { 
      answer.append(inputLine); 
      answer.append("\n"); 
     } 
     in.close(); 

     long elapsed = System.nanoTime() - start; 
     System.out.println("Elapsed (ms): " + elapsed/1000000); 
     System.out.println("Answer:"); 
     System.out.println(answer); 
    } catch (SocketTimeoutException e) { 
     System.out.println("More than " + TIMEOUT_VALUE + " elapsed."); 
    } 
+1

感謝這似乎工作,爲增加的措施,我檢查是否經過的時間少於超時值之前,我將它添加到成功列表。再次感謝! – Austin

1

我用

System.getProperties().put("proxySet", "true"); 
    System.getProperties().put("http.proxyHost", "192.168.10.121"); 
    System.getProperties().put("http.proxyPort", "8080"); 
    //System.getProperties().put("http.nonProxyHosts", "8080"); 
+0

對我有用。您還可以使用Proxy類來限制副作用,而不是更改系統屬性(尤其是在多線程環境中,如服務器)。 –

相關問題