在很多情況下,有些網路應用的需求會要求類比人在不同地區訪問網站和應用。因而切換IP也就應運而生了,然而IP作為一種稀缺資源不是隨便可以獲得的。因而會想到應用程式切換VPN來達到全國不同地區訪問網路。因而有了以下方案。
前提:
1、windows作業系統
2、手工建立網路連接
package com.selenium.test;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;public class ConnectNetWork { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub connAdsl("VPN_Test","test", "test"); Thread.sleep(1000); cutAdsl("VPN_Test"); Thread.sleep(1000); } /** * 執行CMD命令,並返回String字串 */ public static String executeCmd(String strCmd) throws Exception { System.out.println("cmd /c " + strCmd); Process p = Runtime.getRuntime().exec("cmd /c " + strCmd); StringBuilder sbCmd = new StringBuilder(); //這裡很重要,設定GB2312解決亂碼!!! //如果程式預設編碼就是GB2312,可以不寫 //我NetBeans預設用UTF8 BufferedReader br = new BufferedReader(new InputStreamReader(p .getInputStream(), "GB2312")); String line; while ((line = br.readLine()) != null) { sbCmd.append(line + "\n"); } return sbCmd.toString(); /* //如果整個過程換成這樣,就更清楚了。getInputStream是擷取最原始的位元組流, //cmd返回的是以GB2312雙位元組編碼的位元組流 InputStream in = p.getInputStream(); byte[] b = new byte[2000]; in.read(b); String msg = new String(b, "GB2312"); //用GB2312解釋這堆位元組,就可以組裝成一個正常的String了 //如果上邊不寫GB2312,等於這裡用UTF8組裝,結果一樣 return msg; */ } /** * 串連ADSL * 文法: rasdial 串連名稱 username password * 執行個體: rasdial 我的寬頻 hzhz1234567890 dfdfdfdfdf */ public static boolean connAdsl(String adslTitle, String adslName, String adslPass) throws Exception { System.out.println("正在建立串連."); String adslCmd = "rasdial " + adslTitle + " " + adslName + " " + adslPass; String tempCmd = executeCmd(adslCmd); //String tempCmd = executeCmd("ping www.youku.com"); // 判斷是否串連成功 if (tempCmd.indexOf("已串連") > 0) { System.out.println("已成功建立串連."); return true; } else { System.err.println(tempCmd); System.err.println("建立串連失敗"); return false; } } /** * 斷開ADSL */ public static boolean cutAdsl(String adslTitle) throws Exception { String cutAdsl = "rasdial " + adslTitle + " /disconnect"; String result = executeCmd(cutAdsl); if (result.indexOf("沒有串連")!=-1){ System.err.println(adslTitle + "串連不存在!"); return false; } else { System.out.println("串連已斷開"); return true; } } }
說明:上述程式碼片段其實是調用了windows的rasdial命令。所以主要的功勞還是rasdial,java只是個外殼。又一次曲線救國。大家有更好的方法嗎?有更好的方法的話請告訴我,^_^