2016-11-29 58 views
0

我在這裏有一個有趣的場景。我有一個代理服務器地址,每次向它發出HTTP請求時都應該爲我提供一個新的退出IP。我注意到,退出IP只會在重啓程序後纔會改變,而不是每次循環迭代。以下是我的來源。重新建立與代理服務器的連接

循環調用getHTML每次迭代:

String result = getHTML("https://wtfismyip.com/text"); 


public static String getHTML(String urlToRead) throws Exception { 
    InetSocketAddress addy = new InetSocketAddress("example.proxy.com", 1234); 
    Proxy proxy = new Proxy(Proxy.Type.HTTP, addy); 
    StringBuilder result = new StringBuilder(); 
    URL url = new URL(urlToRead); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy); 
    conn.setRequestMethod("GET"); 
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
    String line; 
    while ((line = rd.readLine()) != null) { 
     result.append(line); 
    } 
    rd.close(); 
    conn.disconnect(); 
    return result.toString(); 
} 

結果將繼續每次相同IP,直到我重新啓動程序。我覺得像一些流或套接字還沒有關閉,它保持連接活着。

回答

0

找到了我的問題的答案。 TCP套接字保持活動狀態,並允許它在不重新連接的情況下保持與代理的隧道連接。

我需要在代碼的某處添加此語句,我把它放在這個類初始化的開始處。

System.setProperty("http.keepAlive", "false"); 
相關問題