Here I expect to perform a search on Google and get the result as separate output file by using the terminal. In the terminal, only the keyword to be searched will be entered. This is what I did.
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class GOOGLE {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter search key");
String key = scan.nextLine();
String keyUpdated = key.replaceAll("\\s", "+");
System.out.println(keyUpdated);
try {
URL url = new URL("https://www.google.lk/search?q=" + keyUpdated);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter(key + ".html"));
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and this is what i got when i entered "computer science" as key word.
java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.google.lk/search?q=computer+science
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at java.net.URL.openStream(URL.java:1045)
at GOOGLE.main(Google.java:23)