java打开默认浏览器网址方法

不使用 java.awt.Desktop API,打开默认浏览器访问指定链接的方法

在 Java SE 6 中提供了一套桌面 API 实现与本机桌面 API 的无缝集成,这些桌面 API 使用你的主机操作系统的文件关联以启动与特定文件类型相关联的应用程序。但是因为目前许多客户端并没有安装、部署 JRE 6.0 之后的 Java 运行环境,那么在旧的运行环境中怎样才能调用默认浏览器打开指定的链接呢?

这就是本文的主要内容。

我们把目标平台暂定为 Windows XP 和 Mac OS X。

Windows 平台

可以在控制台中使用 rundll32.exe 调用 url.dll 这个动态连接库打开浏览器访问指定的链接。那么,我们在 Java 程序中就可以使用 Runtime.exec 方法来调用这个命令。(关于 Runtime.exec 可以参考我 blog 中的另一篇文章:Java 程序调用 exe)
 1 String cmd = "rundll32 url.dll,FileProtocolHandler http://www.apple.com";
 2 Runtime.getRuntime().exec(cmd);
 3 
 4 当然,以上程序执行前,首先得判断当前的操作系统平台是否是 Windows。
 5 
 6     private static final String WIN_ID = "Windows";
 7     
 8     public static boolean isWindowsPlatform() ...{
 9         String os = System.getProperty("os.name");
10         
11         if ( os != null && os.startsWith(WIN_ID))
12             return true;
13         else
14             return false;
15     }
16 
17 
18 Mac OS X
19 
20 在 Mac 里稍微有些复杂。同样,我们需要判断当前操作系统平台是否是 Mac OS X。
21 
22     private static final String MAC_ID = "Mac";
23 
24     public static boolean isMacPlatform() ...{
25         String os = System.getProperty("os.name");
26         
27         if ( os != null && os.startsWith(MAC_ID))
28             return true;
29         else
30             return false;
31     }



Apple 公司实现的 JDK 里有这么一个类:com.apple.mrj.MRJFileUtils,在 Mac 下可以使用它提供的方法 openURL 打开浏览器访问链接。为了使我们的程序兼容标准 Java 运行环境,所以使用反射技术来使用这个方法。

   
public static void openMacURL(String url) ...{
        try...{
            Class MRJFileUtils = Class.forName("com.apple.mrj.MRJFileUtils");
            Method openMethod = MRJFileUtils.getDeclaredMethod("openURL", new Class[] ...{String.class});
            openMethod.invoke(MRJFileUtils,new Object[]...{formatString(url)});
        } catch(Exception e) ...{
            e.printStackTrace();
        }
    }

formatString( String ) 顾名思义是用来重新格式化目标 URL。

    public static String formatString(String str) ...{
        String retString="";
        String protocol = "";
        String host = "";
        String path = "";
        
        try ...{
            java.net.URL url = new java.net.URL(str);
            protocol = url.getProtocol();
            host = url.getHost();
            path = url.getPath();
        } catch (MalformedURLException ex) ...{
            path = str;
        }
        
        for(int i = 0; i < path.length(); i++) ...{
            if(path.charAt(i) == ' ') ...{
                retString += "%20";
            } else if(path.charAt(i) == '.') ...{
                retString += "%2E";
            } else ...{
                retString += path.substring(i, i + 1);
            }
        }
        
        if (!protocol.equals("")) ...{
            retString = protocol + "://" + host + retString;
        } else ...{
            retString = host + retString;
        }
        
        return retString ;
    }
posted @ 2012-02-11 22:38  乌冬  阅读(2260)  评论(0编辑  收藏  举报