java调用浏览器

来源:互联网 发布:只知新浪博客呢称 编辑:程序博客网 时间:2024/05/28 11:50

1:这种方法没有测试没有成功,希望有大侠来补充完成的代码

URL url = new URL(applet.getDocumentBase(), "http://....");   
  applet.getAppletContext().showDocument(url,"Test" );

2:是Runtime和DeskTop这两种比较常用的方式,DestTop需要jdk1.6支持

(1)采用Runtime的方式



import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

import javax.swing.JOptionPane;

public class TestUrl {
public TestUrl() {

openURL("http://www.163.com/");
}

public static void openURL(String url) {
try {
browse(url);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error attempting to launch web browser:\n" + e.getLocalizedMessage());
}
}

private static void browse(String url) throws ClassNotFoundException, IllegalAccessException,
IllegalArgumentException, InterruptedException, InvocationTargetException, IOException,
NoSuchMethodException {
String osName = System.getProperty("os.name", "");
if (osName.startsWith("Mac OS")) {
Class fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });
openURL.invoke(null, new Object[] { url });
} else if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
} else { // assume Unix or Linux
String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new NoSuchMethodException("Could not find web browser");
else
Runtime.getRuntime().exec(new String[] { browser, url });
}
}



public static void main(String[] args) {
TestUrl testUrl = new TestUrl();
}
}


(2)采用DeskTop的方式

public class TestUrl {
    public static void main(String[] args) {
        //判断当前系统是否支持Java AWT Desktop扩展
        if(java.awt.Desktop.isDesktopSupported()){
            try {
                //创建一个URI实例
                java.net.URI uri = java.net.URI.create("http://www.163.com/"); 
                //获取当前系统桌面扩展
                java.awt.Desktop dp = java.awt.Desktop.getDesktop();
                //判断系统桌面是否支持要执行的功能
                if(dp.isSupported(java.awt.Desktop.Action.BROWSE)){
                    //获取系统默认浏览器打开链接
                    dp.browse(uri);    
                }
            } catch(java.lang.NullPointerException e){
                //此为uri为空时抛出异常
            } catch (java.io.IOException e) {
                //此为无法获取系统默认浏览器
            }             
        }
    }
}


原创粉丝点击