Rectangle 27 0

java easiest (legal) way to programmatically get the google search result count?

/**** @author RAJESH Kharche */
//open Netbeans
//Choose Java->prject
//name it GoogleSearchAPP

package googlesearchapp;

import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class GoogleSearchAPP {
    public static void main(String[] args) {
        try {
            // TODO code application logic here

            final int Result;

            Scanner s1=new Scanner(;
            String Str;
            System.out.println("Enter Query to search: ");//get the query to search

            System.out.println("Results:"+ Result);
        } catch (IOException ex) {
            Logger.getLogger(GoogleSearchAPP.class.getName()).log(Level.SEVERE, null, ex);

    private static int getResultsCount(final String query) throws IOException {
        final URL url;
        url = new URL("" + URLEncoder.encode(query, "UTF-8"));
        final URLConnection connection = url.openConnection();

        connection.addRequestProperty("User-Agent", "Google Chrome/36");//put the browser name/version

        final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8");  //scanning a buffer from object returned by http request

        while(reader.hasNextLine()){   //for each line in buffer
            final String line = reader.nextLine();

            if(!line.contains("\"resultStats\">"))//line by line scanning for "resultstats" field because we want to extract number after it

                return Integer.parseInt(line.split("\"resultStats\">")[1].split("<")[0].replaceAll("[^\\d]", ""));//finally extract the number convert from string to integer
        return 0;

@DavidH.Bennett Any reason why the difference?

I just tried Josh's code, didn't work. Tried Rajesh's class and it did.

You seem to have reused the code from the answer by @JoshM. However, you have modified and extended the code. What was the reason to do so? What does your code better/differently than that of @JoshM? Such kind of explanation would help readers to understand your solution.

hey if you want me to sent you the content returned by link in the object i surely will.