我正在尝试在带有 silvertunnel-ng 库的 Java 应用程序中通过 Tor 阅读网站。连接似乎已建立(日志显示“开始完成!”),但是当我尝试阅读该站点时,我得到一个
java.net.ProtocolException: Server redirected too many times (3)
测试代码是这样的:
String torCheck = "https://check.torproject.org/?lang=en_US";
URLStreamHandler handler = TorTools.buildTorHandler();
String result = "";
try {
URL url = new URL(null, torCheck, handler);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
System.setProperty("http.maxRedirects", "20");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while (br.read() != -1)
result += br.readLine() + "\n";
} catch (IOException e) {
...
} finally {
...
}
System.out.println(result);
显然 httpRedirects 属性没有设置,因为堆栈跟踪仍然显示“(3)”,但我不知道为什么。
此处建议添加 CookieHandler ,但无济于事。
Tor 处理程序是使用以下方法构建的:
import org.silvertunnel_ng.netlib.adapter.url.NetlibURLStreamHandlerFactory;
import org.silvertunnel_ng.netlib.api.NetFactory;
import org.silvertunnel_ng.netlib.api.NetLayer;
import org.silvertunnel_ng.netlib.api.NetLayerIDs;
public static URLStreamHandler buildTorHandler() {
NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TOR);
netLayer.waitUntilReady();
NetlibURLStreamHandlerFactory factory = new NetlibURLStreamHandlerFactory(false);
factory.setNetLayerForHttpHttpsFtp(netLayer);
return factory.createURLStreamHandler("http");
}
任何想法将不胜感激。