在Java中通过Google搜索字符串并提交。

huangapple go评论86阅读模式
英文:

Search strings on google through Java and submit

问题

我正在尝试创建一个程序,用于向Google提交搜索查询,然后打开带有搜索结果的浏览器。
我已经成功连接到Google,但我卡住了,因为我不知道如何将搜索查询插入URL并提交它。
我尝试使用HtmlUnit,但似乎不起作用。

到目前为止的代码如下:

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

I'm trying to make a program that submits a search query to Google and then opens the browser with the results.
I have managed to connect to Google but I'm stuck because I don't know how to insert the search query into the URL and submit it.
I have tried to use HtmlUnit but it doesn't seem to work.

This is the code so far:

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

答案1

得分: 0

你可以使用Java.net包来浏览互联网。我已经使用了额外的方法来为Google创建搜索查询,以将空格替换为URL地址中的%20。

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;
英文:

You can use the Java.net package to browse the internet. I have used an additional method to create the search query for google to replace the spaces with %20 for the URL address

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;
}

The packages used are core java:

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

huangapple
  • 本文由 发表于 2020年8月19日 16:21:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63482850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定