Google Custom search API: how to get search result contents description (e.g snippets) for URL

StackOverflow https://stackoverflow.com/questions/22789452

  •  25-06-2023
  •  | 
  •  

Question

how can we get the contents of the URL retrieved using google custom search API. I am new to work with such APIs and in documentation no such sample code is given that can explain it. I am using google-api-services-customsearch-v1-rev36-1.17.0-rc.jar here is my code.

protected Result[] doSearch() {

    HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer(){   
        @Override
        public void initialize(HttpRequest request) throws IOException {
        }
    };

    JsonFactory jsonFactory = new JacksonFactory();
    Customsearch csearch = new Customsearch( new  NetHttpTransport(),  jsonFactory,  httpRequestInitializer);


    Customsearch.Cse.List listReqst = csearch.cse().list(query.getQueryString());
    listReqst.setKey(GOOGLE_KEY);
    // set the search engine ID got from API console
    listReqst.setCx("SEARCH_ENGINE_ID"); 

    // set the query string
    listReqst.setQ(query); //query contains search query string

    // language chosen is English for search results 
    listReqst.setLr("lang_en"); 
    // set hit position of first search result 
    listReqst.setStart((long) firstResult);  
    // set max number of search results to return
    listReqst.setNum((long) maxResults);

    Search result = list.execute();
    // perform search
}

here after this need to get the snippets and URLs of the corresponding websites. which I have to return in this function. how can we retrieve them.

Était-ce utile?

La solution

In the final line of your code it executes the query, returns the results, and parses them into that 'Search' object, described here:
https://developers.google.com/resources/api-libraries/documentation/customsearch/v1/java/latest/com/google/api/services/customsearch/model/Search.html

So, to get the URL and snippet for each result you just do:

List<Result> results = result.getItems();
for (Result r : results) {
  String url = r.getLink();
  String snippet = r.getSnippet();
}

To return all the Results, as per your function signiture above, you just need to convert the list to an array:

List<Result> results = result.getItems();
return results.toArray( new Result[results.size()] );
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top