java - 通过 VPN/代理的 JSoup

标签 java proxy httpclient jsoup vpn

我正在尝试使用 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/

相关文章:

java - 在 Android 中使用 HttpPost 发送对象数组

java - 正则表达式 - 如果一个字符后跟另一个字符,则只选择一个字符

java - 在 Android 上将 OAuth 与 Scribe 结合使用

java - (70007)指定的超时已过期 : proxy: error reading status line from remote server

java - 管理身份验证 token 的最佳实践

c# httpclient POST 请求 : cant send special characters

java - 用Java中的步骤迭代LinkedList

java - 为什么我的 Kafka 消费者投票这么快?

node.js - 如何覆盖 node.js http 以对所有出站请求使用代理

php - 通过代理使用 https 请求的 file_get_contents