-1

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!";
Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
LAC
  • 47
  • 5
  • 1
    open your web browser, go to http://google.com, search for anything, look at the corresponding url, adapt it – jhamon Aug 19 '20 at 08:27
  • Added syntax highlighting, fixed spelling and grammar. It is now more clear the the user wants to insert a *search query* into the *URL* and not into the search bar, which is only a UI concept but which they probably confused with the URL. – Jan Schultke Aug 20 '20 at 07:49

1 Answers1

0

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;
0009laH
  • 1,960
  • 13
  • 27
Aneesh
  • 148
  • 1
  • 10