Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java code for using google custom search API

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.

like image 802
dark_shadow Avatar asked Apr 21 '12 07:04

dark_shadow


People also ask

How do I use Google Custom Search API?

Custom Search JSON API requires the use of an API key. An API key is a way to identify your client to Google. After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs. The API key is safe for embedding in URLs, it doesn't need any encoding.

How do I get a Google Custom Search API key?

You can get an API key by visiting https://code.google.com/apis/console and clicking "API Access". You will then need to switch on the custom search API on the "Services" tab.

Is there a Google API for search?

The Search Console API provides programmatic access to the most popular reports and actions in your Search Console account. Query your search analytics, list your verified sites, manage your sitemaps for your site, and more. Official Google Search updates and SEO best practices.


2 Answers

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.

like image 191
Pargat Avatar answered Nov 16 '22 01:11

Pargat


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'
}
like image 30
Martino Avatar answered Nov 16 '22 03:11

Martino