如何使用Tor与Java结合使用

时间:2015-04-15 15:00:32

标签: java autorotate tor

更新了我的问题

我正在通过Java构建一个爬虫系统来在线比较价格。但是,我担心我的IP地址可以被禁止。所以我打算使用代理来更改IP动态或使用一些工具自动轮换IP。

很多人都说TOR是一种强大的IP轮换工具。但是,我不知道如何使用Tor以及如何将Tor集成到Java Web应用程序中?

我已经搜索了Google以找到示例,但仍然没有找到任何有用的内容。

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:14)

当它发出使用URL的传出HTTP连接时,您只需要让Java在localhost:8118(8118是默认的Tor端口)上使用SOCKS4代理(使用URLConnection ),Tor服务正在运行。有关如何在Java 8中使用代理,请参阅here

编辑:您也可以使用this pure Java Tor library直接或通过微小修改(如果它的行为完全类似于普通的本机Tor服务),但它还没有更新一段时间可能与最新的Tor规范不兼容。

HttpClient示例:

HttpHost proxy = new HttpHost("127.0.0.1", 8118, "http");

DefaultHttpClient httpclient = new DefaultHttpClient();
try {
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpHost target = new HttpHost("www.google.com", 80, "http");
    HttpGet req = new HttpGet("/");

    System.out.println("executing request to " + target + " via " + proxy);
    HttpResponse rsp = httpclient.execute(target, req);
    ...
} finally {
    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

请注意,必须为此运行Tor服务。