
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;

public class GoogleSearchAPI
{
  // How to use
  public static void main(String[] args){
    // Key word for search
    String keys = "福岡工大";

    GoogleSearchAPI obj = new GoogleSearchAPI();
    long n = obj.getNumHits(keys);
    System.out.println("Keys:"+keys+", Hits:" + n);   
  }

  // Fields
  private String api;       // API Key
  private String engine_id; // Search Engine ID
  private String filepath2api = "apikey\\custom_search_api.txt";
  private String filepath2engine_id = "apikey\\engine_id.txt";

  // Constructor
  public GoogleSearchAPI(){
    // Loading API key and Engine ID
    try{
      BufferedReader br;
      br = new BufferedReader(new FileReader(filepath2api));
      api = br.readLine();
      br.close();
      br = new BufferedReader(new FileReader(filepath2engine_id));
      engine_id  = br.readLine();
      br.close();
    }catch(IOException e){
      // No hits will be obtained if the keys cannot be loaded.
      api = null;
      engine_id = null;
    }
  }

  // Primary method
  public long getNumHits(String keys)
  {
    long numHits = 0;
    try{
      URL url = new URL("https://www.googleapis.com/customsearch/v1?q="+keys.replace(" ","+")+"&key="+api+"&cx="+engine_id);
      HttpURLConnection con = (HttpURLConnection)url.openConnection();
      con.setRequestMethod("GET");

      BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
      StringBuilder res = new StringBuilder();
      String str;
      while ((str = br.readLine()) != null){
        res.append(str);
      }
      br.close();

      JSONObject json = new JSONObject(res.toString());
      numHits = Long.parseLong(json.getJSONObject("searchInformation").getString("totalResults"));
      
      // System.out.println("総ヒット数: " + totalResults);
    } catch (Exception e) {
      System.out.println(e);
      numHits = 0;
    }
    return(numHits);
  }
}
