12

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.

dark_shadow
  • 3,503
  • 11
  • 56
  • 81
  • Possible duplicate http://stackoverflow.com/q/3727662/776084 – RanRag Apr 21 '12 at 08:14
  • 1
    @RanRag:I dnt think it's a duplicate since here I know about Google custom search API.The only thing I'm asking is some good java codes to get started with it. – dark_shadow Apr 21 '12 at 08:22

3 Answers3

14

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.

Pargat
  • 769
  • 9
  • 23
  • 2
    i get links details, but have you know any way to get webpage details which are open from these links. – Aniket Mar 30 '13 at 13:14
  • This is giving me an HTTP error code of 400. Is there a limit to how many queries you can make per day? If so, what is that limit? – Mike Warren Oct 17 '14 at 07:15
  • @Pargat i am getting `java.io.IOException: Server returned HTTP response code: 403` help me to solve this, i used above code only – Selva Aug 20 '15 at 11:50
  • How to retrieve next page on this req? – Nobody Aug 08 '17 at 23:09
11

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'
}
Martino
  • 111
  • 1
  • 5
  • 2
    Thanks for the answer! I am actually dealing right now with this, and found your code useful. I like how you set the API key and search engine ID, rather than using the URL String as in other answers. – evaldeslacasa Oct 30 '17 at 22:23
4

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.

Zakaria
  • 14,892
  • 22
  • 84
  • 125
  • I run the code but the output is not according to my expectation.I thought I would get some top links from the code.Can you tell me how can I achieve that from this code ? – dark_shadow Apr 21 '12 at 10:35
  • 1
    @Zakaria i get links details, but have you know any way to get webpage details which are open from these links. – Aniket Mar 30 '13 at 13:14