介紹:
我使用v1https://developers.google.com/custom-search/v1/overview
準備工作:
只要有Google 帳號就能申請,但一天只能免費查詢100次申請設定custom search engine並取得engine ID
申請Google API使用權限並取得 API key
作法概念:
發出Http GET request 到下面的URL並設定好參數https://www.googleapis.com/customsearch/v1?key=[INSERT-YOUR-API-KEY]&cx=[CUSTOM-SEARCH-ENGINE-ID]
範例程式:
public String search(String keyword){ StringBuffer result = new StringBuffer(); try { HttpURLConnection connection = (HttpURLConnection)new URL(CSE_URL+"&q="+keyword).openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine())!=null){ result.append(line); } }catch (Exception e) { e.printStackTrace(); } return result.toString(); }
使用 Custom Search API - Java library:
Javadoc使用 library的好處是可以用物件存取查詢的結果,不用處理Json object。
官方沒有任何範例程式。勉強找到一個堪用的範例:
http://stackoverflow.com/questions/6917861/java-google-custom-search-api
public Listsearch(String keyword){ Customsearch customsearch = new Customsearch(new NetHttpTransport(), new JacksonFactory()); List resultList = null; try { Customsearch.Cse.List list = customsearch.cse().list(keyword); list.setKey(API_KEY); list.setCx(CSE_ID); Search results = list.execute(); resultList = results.getItems(); }catch (Exception e) { e.printStackTrace(); } return resultList; }
留言