通过java在google上搜索字符串并提交

jutyujz0  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(202)

我正在尝试制作一个程序,向google提交一个搜索查询,然后打开带有结果的浏览器。我已经设法连接到谷歌,但我卡住了,因为我不知道如何插入搜索查询到网址和提交它。我试过使用htmlunit,但似乎不起作用。
这是目前为止的代码:

URL url = new URL("http://google.com");
HttpURLConnection hr = (HttpURLConnection) url.openConnection();
System.out.println(hr.getResponseCode());
String str = "search from java!";
j13ufse2

j13ufse21#

您可以使用java.net包浏览互联网。我使用了一个额外的方法来创建google的搜索查询,用%20替换url地址的空格

public static void main(String[] args)  {
    URI uri= null;
    String googleUrl = "https://www.google.com/search?q=";
    String searchQuery = createQuery("search from Java!");
    String query = googleUrl + searchQuery;

    try {
        uri = new URI(query);
        Desktop.getDesktop().browse(uri);
    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }
}

private static String createQuery(String query) {
    query = query.replaceAll(" ", "%20");
    return query;
}

使用的包是核心java:

import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxException;

相关问题