我正在尝试使用 JSoup 抓取暂存服务器上的一些页面。要使用浏览器查看登台服务器上的页面,我需要连接到 VPN。
我已连接到 VPN,但当我使用 JSoup 尝试抓取页面时,它总是超时。如何让我的程序使用 VPN 连接。还是这里有其他我没有想到的东西?
注意:我还在程序的另一部分使用了 HttpClient。有没有一种方法可以设置我的程序在程序初始化后连接到 VPN/代理,以便 JSoup 和 HttpClient 都使用 VPN/代理。
谢谢
最佳答案
您可以为代理设置 java 属性:
// if you use https, set it here too
System.setProperty("http.proxyHost", "<proxyip>"); // set proxy server
System.setProperty("http.proxyPort", "<proxyport>"); // set proxy port
Document doc = Jsoup.connect("http://your.url.here").get(); // Jsoup now connects via proxy
或者将网站下载成字符串然后解析:
final URL website = new URL("http://your.url.here"); // The website you want to connect
// -- Setup connection through proxy
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<proxyserver>", 1234)); // set proxy server and port
HttpURLConnection httpUrlConnetion = (HttpURLConnection) website.openConnection(proxy);
httpUrlConnetion.connect();
// -- Download the website into a buffer
BufferedReader br = new BufferedReader(new InputStreamReader(httpUrlConnetion.getInputStream()));
StringBuilder buffer = new StringBuilder();
String str;
while( (str = br.readLine()) != null )
{
buffer.append(str);
}
// -- Parse the buffer with Jsoup
Document doc = Jsoup.parse(buffer.toString());
对于此解决方案,您也可以使用 HttpClient
。
关于java - 通过 VPN/代理的 JSoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13288471/