zoukankan      html  css  js  c++  java
  • 常用代码块:java使用系统浏览器打开url

    方法一:用于windows

    try {
    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+url);
    } catch (IOException e1) {
    e1.printStackTrace();
    }

    方法二:通用,但会可能会抛出java.net.URISyntaxException异常。

    try {
    // 创建一个URI实例,注意不是URL url格式问题可能会有异常这里
    java.net.URI uri = java.net.URI.create(url);
    // 获取当前系统桌面扩展
    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 (Exception e) {
    e.printStackTrace();
    // 此为无法获取系统默认浏览器
    }

    下边这个方法比较保险:

    String url = "https://127.0.0.1:8834";
    if (!url.startsWith("http")) {
    url = "http://" + url;
    }

    try {
    // 创建一个URI实例,注意不是URL
    java.net.URI uri = java.net.URI.create(url);
    // 获取当前系统桌面扩展
    java.awt.Desktop dp = java.awt.Desktop.getDesktop();
    // 判断系统桌面是否支持要执行的功能
    if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
    // 获取系统默认浏览器打开链接
    dp.browse(uri);
    }
    } catch (IllegalArgumentException e) {
    e.printStackTrace();

    try {
    Class<URI> clazz = URI.class;
    Field path = clazz.getDeclaredField("path");
    Field schemeSpecificPart = clazz.getDeclaredField("schemeSpecificPart");
    Field string = clazz.getDeclaredField("string");
    path.setAccessible(true);
    schemeSpecificPart.setAccessible(true);
    string.setAccessible(true);

    int i = url.indexOf("//");
    String strSchemeSpecificPart = url.substring(i);

    String s = strSchemeSpecificPart.substring(2);
    int j = s.indexOf("/");
    String strpath = s.substring(j);

    String scheme = url.substring(0, i + 2);
    String host = s.substring(0, j);
    host = host.trim();
    URI uri = URI.create(scheme + host);

    path.set(uri, strpath);
    schemeSpecificPart.set(uri, strSchemeSpecificPart);
    string.set(uri, url);
    java.awt.Desktop dp = java.awt.Desktop.getDesktop();
    // 判断系统桌面是否支持要执行的功能
    if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
    // 获取系统默认浏览器打开链接
    dp.browse(uri);
    }

    } catch (Exception ee) {

    }

    } catch (java.lang.NullPointerException e) {
    // 此为uri为空时抛出异常
    } catch (java.io.IOException e) {
    // 此为无法获取系统默认浏览器
    }

  • 相关阅读:
    MySQL select语句中where条件的提取过程
    MySQL特性:ICP,Index Condition Pushdown
    MySQL特性:BKA,Batched Key Access,批量索引访问
    MySQL特性:MRR,Multi-Range Read,多范围读
    show engine innodb status 输出结果解读
    IPv6的一点使用小计
    MySQL 通过ibd恢复数据
    explain 小结
    clickhouse的多路径存储策略
    cenos6.5升级glibc2.18
  • 原文地址:https://www.cnblogs.com/fsqsec/p/5698306.html
Copyright © 2011-2022 走看看