Search code examples
javahtmlsearchbrowserheadless

Search strings on google through Java and submit


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!";

Solution

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