柱塞阀用在蒸汽上:VPN连接的JAVA代码

来源:百度文库 编辑:中财网 时间:2024/04/28 06:58:49

VPN连接的JAVA代码

发表于 September 26, 2011 in JAVA and 小技巧. 4 Comments Tags: JAVA, windows, 基础, 网络.

在写爬虫时常常被ban,如淘宝这样的网站如果请求并发过快就很快被ban了,一ban就很久,而幸好我们没有固定IP,在VPN或者ADSL重连后IP就变化了,可以继续爬数据而不会被ban。

Windows提供了一个rasdial的命令,可以连接VPN和断开VPN。

首先需要新建一个VPN,如建立了一个名称为“VPN”的连接。

写了一个VPNTool的JAVA类

view plaincopy to clipboardprint?
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStreamReader;  
  4.   
  5. public class VPNTool  
  6. {  
  7.     private synchronized static String executeCmd(String cmd) throws IOException  
  8.     {  
  9.         Process process = Runtime.getRuntime().exec("cmd /c " + cmd);  
  10.         StringBuilder sbCmd = new StringBuilder();  
  11.         BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));  
  12.         String line = "";  
  13.         while ((line = br.readLine()) != null)  
  14.         {  
  15.             sbCmd.append(line);  
  16.         }  
  17.         return sbCmd.toString();  
  18.     }  
  19.   
  20.     public synchronized static boolean disconnectVPN(String vpnName) throws IOException  
  21.     {  
  22.         String cmd = "rasdial " + vpnName + " /disconnect";  
  23.         String result = executeCmd(cmd);  
  24.   
  25.         if (result == null || result.contains("没有连接"))  
  26.             return false;  
  27.         else return true;  
  28.     }  
  29.     public synchronized static boolean connectVPN(String vpnName, String username, String password) throws IOException  
  30.     {  
  31.         String cmd = "rasdial " + vpnName + " " + username + " " + password;  
  32.         String result = executeCmd(cmd);  
  33.         if (result == null || !result.contains("已连接"))  
  34.             return false;  
  35.         return true;  
  36.     }  
  37.   
  38. }  

调用时只需要VPNTool.connectVPN(“VPN”, “username”, “password”) 就可以连接VPN,调用VPNTool.disconnect(“VPN”)则断开连接。