Java code for using google custom search API

26,445

Solution 1

I have changed the while loop in the code provided by @Zakaria above. It might not be a proper way of working it out but it gives you the result links of google search. You just need to parse the output. See here,

public static void main(String[] args) throws Exception {

    String key="YOUR KEY";
    String qry="Android";
    URL url = new URL(
            "https://www.googleapis.com/customsearch/v1?key="+key+ "&cx=013036536707430787589:_pqjad5hr1a&q="+ qry + "&alt=json");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");
    BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {

        if(output.contains("\"link\": \"")){                
            String link=output.substring(output.indexOf("\"link\": \"")+("\"link\": \"").length(), output.indexOf("\","));
            System.out.println(link);       //Will print the google search links
        }     
    }
    conn.disconnect();                              
}

Hope it works for you too.

Solution 2

For anyone who would need working example of Custom search API using Google library, you can use this method:

public static List<Result> search(String keyword){
    Customsearch customsearch= null;


    try {
        customsearch = new Customsearch(new NetHttpTransport(),new JacksonFactory(), new HttpRequestInitializer() {
            public void initialize(HttpRequest httpRequest) {
                try {
                    // set connect and read timeouts
                    httpRequest.setConnectTimeout(HTTP_REQUEST_TIMEOUT);
                    httpRequest.setReadTimeout(HTTP_REQUEST_TIMEOUT);

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
    List<Result> resultList=null;
    try {
        Customsearch.Cse.List list=customsearch.cse().list(keyword);
        list.setKey(GOOGLE_API_KEY);
        list.setCx(SEARCH_ENGINE_ID);
        Search results=list.execute();
        resultList=results.getItems();
    }
    catch (  Exception e) {
        e.printStackTrace();
    }
    return resultList;
}

This method returns List of Result objects, so you can iterate through it

    List<Result> results = new ArrayList<>();

    try {
        results = search(QUERY);
    } catch (Exception e) {
        e.printStackTrace();
    }
    for(Result result : results){
        System.out.println(result.getDisplayLink());
        System.out.println(result.getTitle());
        // all attributes:
        System.out.println(result.toString());
    }

As you have noticed, you have to define your custom GOOGLE_API_KEY, SEARCH_ENGINE_ID, QUERY and HTTP_REQUEST_TIMEOUT, ie

private static final int HTTP_REQUEST_TIMEOUT = 3 * 600000;

I use gradle dependencies:

dependencies {
compile 'com.google.apis:google-api-services-customsearch:v1-rev57-1.23.0'
}

Solution 3

Well, I think that there is nothing special in the sense that you can use a Java RESTFUL client.

I tried the Custom API using that Java code and basing on the Google documentation :

public static void main(String[] args) throws IOException {
        URL url = new URL(
                "https://www.googleapis.com/customsearch/v1?key=YOUR-KEY&cx=013036536707430787589:_pqjad5hr1a&q=flowers&alt=json");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();
    }

You have to replace "YOUR-KEY" with a one found on the Google APIs Console.

Share:
26,445
dark_shadow
Author by

dark_shadow

Updated on July 05, 2022

Comments

  • dark_shadow
    dark_shadow almost 2 years

    Can anyone please share some java codes for getting started with google search api's.I searched on Internet but not found any proper documentation or good sample codes.The codes which I found doesn't seem to be working.I'll be thankful if anyone can help me.(I have obtained API key and custom search engine id).

    Thanks.