JSoup通过VPN /代理

5
我想使用JSoup爬取位于测试服务器上的一些页面。想要通过浏览器查看此类页面,则需要连接VPN。
我已经连接到VPN,但是当我使用JSoup尝试爬取页面时,程序会一直超时。那么如何使程序使用VPN连接呢?或者,还有其他我没有考虑的问题吗?
注意:我的程序中还使用了HttpClient。是否可以在程序初始化后设置连接到VPN/代理,以便JSoup和HttpClient都使用VPN/代理?
谢谢

1
如果您的 HttpClient 在代理上运行,您可以使用它将网站下载到字符串中并解析它(就像我的答案中的解决方案#2)。 - ollo
3个回答

9

您可以为代理设置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来实现此解决方案。

6

3
如需为代理服务器添加用户名/密码验证,请参考以下步骤:
final String authUser = <username>;
final String authPassword = <password>;
Authenticator.setDefault(
   new Authenticator() {
      public PasswordAuthentication getPasswordAuthentication() {
         return new PasswordAuthentication(
               authUser, authPassword.toCharArray());
      }
   }
);

System.setProperty("http.proxyHost", <yourproxyhost>);
System.setProperty("http.proxyPort", <yourproxyport>);
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);

Document doc = Jsoup.connect("http://your.url.here").get();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接