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.

2
  • Possible duplicate stackoverflow.com/q/3727662/776084 Commented Apr 21, 2012 at 8: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. Commented Apr 21, 2012 at 8:22

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

i get links details, but have you know any way to get webpage details which are open from these links.
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?
@Pargat i am getting java.io.IOException: Server returned HTTP response code: 403 help me to solve this, i used above code only
How to retrieve next page on this req?
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'
}

1 Comment

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.
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.

2 Comments

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 ?
@Zakaria i get links details, but have you know any way to get webpage details which are open from these links.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.