@@ -43,39 +43,39 @@ make all SERPAPI_KEY='<your private key>'
4343Use quotes if your key contains shell-special characters. You need a SerpApi account to obtain a key: https://serpapi.com/dashboard
4444
4545` demo/src/main/java/demo/App.java ` :
46- ``` java
47- public class App {
48- public static void main (String [] args ) throws SerpApiException {
49- if (args. length != 1 ) {
50- System . out. println(" Usage: app <secret api key>" );
51- System . exit(1 );
52- }
46+ ``` javapublic
47+ class App {
48+ public static void main(String[] args) {
49+ String apiKey = System.getenv("SERPAPI_KEY");
5350
51+ // set search location
5452 String location = "Austin,Texas";
55- System . out. println(" find the first Coffee in " + location);
53+ String engine = "google";
54+ System.out.println("find the first coffee shop in " + location + " using " + engine);
5655
57- // set api_key provided by the command line
5856 Map<String, String> auth = new HashMap<>();
59- auth. put(" api_key" , args[0 ]);
57+ auth.put("engine", engine);
58+ auth.put("api_key", apiKey);
6059
61- // Create search
60+ // create client
6261 SerpApi serpapi= new SerpApi(auth);
6362
63+ // create search parameters
6464 Map<String, String> parameter = new HashMap<>();
6565 parameter.put("q", "Coffee");
6666 parameter.put("location", location);
6767
68+ // perform search
6869 try {
69- // Perform search
70- JsonObject data = serpapi. search(parameter);
71-
72- // Decode response
73- JsonArray results = data. get(" local_results" ). getAsJsonObject(). get(" places" ). getAsJsonArray();
74- JsonObject first_result = results. get(0 ). getAsJsonObject();
75- System . out. println(" first coffee shop: " + first_result. get(" title" ). getAsString() + " found on Google in " + location);
70+ // get search results
71+ JsonObject data = serpapi.search(parameter);
72+ JsonArray organic = data.getAsJsonArray("organic_results");
73+ JsonObject first = organic.get(0).getAsJsonObject();
74+ System.out.println("First result: " + first.get("title").getAsString() + " (search near " + location + ")");
7675 } catch (SerpApiException e) {
77- System . out. println(" oops exception detected! " );
76+ System.out.println("SerpApi request failed. ");
7877 e.printStackTrace();
78+ System.exit(1);
7979 }
8080 }
8181}
0 commit comments