在java

时间:2017-02-15 19:41:01

标签: java http-redirect tor silvertunnel

我正在尝试使用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属性没有设置,因为stacktrace仍然说“(3)”,但我不明白为什么。

建议添加CookieHandler here,但无济于事。

使用此方法构建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");
}

任何想法都会非常感激。

0 个答案:

没有答案