Search code examples
javaandroidjsonajaxgoogle-search-api

Searching google programmatically without ajax


Apparently google retired the ajax api which I have been using in java for android, I dug through their new API page but I can't find anything that seems to work in java, or any non-web language for that matter.

This is what I had previously:

@Override
protected String doInBackground(String... query) {
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new URL("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + URLEncoder.encode(query[0], "UTF-8")).openStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        reader.close();

        return sb.toString();
    }
    catch(Exception e){e.printStackTrace();
        return "failed to do anything";
    }
}

Simply put, a string is supplied, and appended to the ajax search. The results, in JSON form, are processed into a string builder and then returned as a whole string.

If you attempt to do this now, it returns this result:

{"responseData": null, "responseDetails": "The Google Web Search API is no longer available. Please migrate to the Google Custom Search API (https://developers.google.com/custom-search/)", "responseStatus": 403}

Again, I have read the custom search API but have not found anything that will work outside javascript.

I'd prefer a JSON solution, since that's what I'm using already but I can work with whatever I get.

So, is there some alternative that I can use a similar method with? Or am I going to be forced into another search engine?

//EDIT

Okay, so I now have the fixed code. However it requires an API key, which I can't be posting in my open source project, and its a limited amount of searches unless I pay, so I'm going to be forced to go to a competitor. Here is the fixed code for anyone interested:

@Override
protected String doInBackground(String... query) {
    try {
        String APIKey = "INSERT_YOUR_API_KEY";
        String customSearchEngine = "INSERT_YOUR_CUSTOM_SEARCH_KEY";
        BufferedReader reader = new BufferedReader(new InputStreamReader(new URL("https://www.googleapis.com/customsearch/v1?key=" + APIKey + "&cx=" + customSearchEngine + "&q=" + URLEncoder.encode(query[0], "UTF-8")).openStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        reader.close();

        return sb.toString();
    }
    catch(Exception e){e.printStackTrace();
        return "failed to do anything";
    }
}

Solution

  • They mention JSON API on that site here

    It is a REST api. Google for "Java REST client" to get some examples on how to use it from Java