Java tutorial
/* Copyright 2009 Jiayao Yu Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.jiayao.reviewfinder; import java.io.IOException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class GoogleSearchEngine implements SearchEngine { private static final String GOOGLE_SEARCH_URL = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q="; private static final String TITLE_NO_FORMATTING = "titleNoFormatting"; private static final String TAG = "GoogleSearchEngine"; private String siteRestriction; public GoogleSearchEngine(String siteRestriction) { this.siteRestriction = siteRestriction; } public Map<String, String> search(String query) throws IOException { Log.i(TAG, "searching " + query); try { JSONArray resultsJsonArray; resultsJsonArray = getJsonArray(Utils .downloadPageContent(new URL(GOOGLE_SEARCH_URL + siteRestriction + URLEncoder.encode(query)))); Map<String, String> results = new HashMap<String, String>(); for (int i = 0; i < resultsJsonArray.length(); i++) { JSONObject resultObj = resultsJsonArray.getJSONObject(i); String title = resultObj.getString(TITLE_NO_FORMATTING); String link = resultObj.getString("url"); results.put(title, link); } return results; } catch (JSONException e) { throw new RuntimeException(e); } } private JSONArray getJsonArray(String content) throws JSONException { JSONObject responseObj = new JSONObject(content).getJSONObject("responseData"); return responseObj.getJSONArray("results"); } public SearchEngine getRefiningSearchEngine() { return null; } }