Pec*_*277 5 java vpn proxy httpclient jsoup
我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)
或者将网站下载到一个字符串中并解析它:
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());
Run Code Online (Sandbox Code Playgroud)
您也可以使用HttpClient此解决方案.
从版本1.9开始,您可以在连接上设置它:https://jsoup.org/apidocs/org/jsoup/Connection.html#proxy-java.net.Proxy-
JSoup.connect("http://your.url.here").proxy("<proxy-host>", <proxy-port>).get();
Run Code Online (Sandbox Code Playgroud)