import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.json.JSONArray; // JSON library from http://www.json.org/java/
import org.json.JSONObject;
public class GoogleQuery {
// Put your website here
int fetchStart = 0;
private final String HTTP_REFERER = "http://www.example.com/";
private String urlString= "";
/*
* fetchSize of n yields n*8 results
*
*/
public GoogleQuery(String query,int fetchStart,int fetchSize) {
buildQuery(query,fetchStart,fetchSize);
}
void buildQuery(String query,int fetchStart,int fetchSize){
for(int i=0;i
this.fetchStart = fetchStart+i*8;
urlString="http://ajax.googleapis.com/ajax/services/search/web?start="+ this.fetchStart +"&rsz=large&v=1.0&q=";
executeQuery(query);
}
}
void executeQuery(String query) {
try
{
// Convert spaces to +, etc. to make a valid URL
query = URLEncoder.encode(query, "UTF-8");
URL url = new URL(urlString + query);
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", HTTP_REFERER);
// Get the JSON response
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
String response = builder.toString();
JSONObject json = new JSONObject(response);
System.out.println("Total results = " + json.getJSONObject("responseData").getJSONObject("cursor")
.getString("estimatedResultCount"));
JSONArray ja = json.getJSONObject("responseData").getJSONArray("results");
for (int i = 0; i < ja.length(); i++) {
System.out.print((i+1) + ". ");
JSONObject j = ja.getJSONObject(i);
System.out.println(j.getString("url"));
}
}
catch (Exception e) {
System.err.println("Something went wrong...");
e.printStackTrace();
}
}
public static void main(String args[]) {
new GoogleQuery("google",0,4);
}
}
No comments:
Post a Comment