[英]I want to open link or URL on browser with Java code
I have a URL(like: " https://www.google.co.in/ ") that should be open on browser(on same browser where my application is running.) at run time from Java code.我有一个 URL(如:“ https://www.google.co.in/ ”),它应该在运行时从 Java 代码在浏览器上打开(在运行我的应用程序的同一浏览器上。)。
Searched many thing and found below java code but it's not working for me.搜索了很多东西,在 java 代码下面找到了,但它对我不起作用。
Desktop desktop = java.awt.Desktop.getDesktop();
URI uri = new URI(String.valueOf("My_Url"));
desktop.browse(uri);
While using above code, i am getting below exception使用上面的代码时,我遇到了异常
java.awt.HeadlessException
at java.awt.Desktop.getDesktop(Desktop.java:142)
Also i have added and tried with below line of code with static block and without static block and getting same exception.我还添加并尝试了下面的代码行,带有 static 块和没有 static 块并得到相同的异常。 Please suggest.
请建议。
System.setProperty("java.awt.headless", "true");
use ProcessBuilder使用 ProcessBuilder
List<String> list = new ArrayList<String>();
list.add("start");
list.add("www.google.com");
ProcessBuilder build = new ProcessBuilder(list);
build.start();
Perhaps this will work?也许这会起作用?
String url = "http://www.google.co.in";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You can use Selenium Web Driver for opening a website into browser.您可以使用 Selenium Web 驱动程序在浏览器中打开网站。 click here to see web driver setup how to setup
点击这里查看 web 驱动设置如何设置
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class OpenSite
{
public static void main(String[] args) throws Exception
{
WebDriver driver=new FirefoxDriver();
// tries to open https://google.com
driver.get("https://google.com");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.