58,452
社区成员




import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.JSONArray;
import org.json.JSONObject;
public class GoogleQuery
{
public GoogleQuery() throws UnsupportedEncodingException
{
String query = URLEncoder.encode("AOP示例+site:blog.csdn.net/zhjb1025", "UTF-8");//站内搜索?
for(int i=0;i<3;i++)
{
makeQuery("http://ajax.googleapis.com/ajax/services/search/web?start="+i*8+"&rsz=large&v=1.0&q="+query);
}
}
private void makeQuery(String query)
{
try
{
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(query);
httpClient.executeMethod(getMethod);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
int statusCode = httpClient.executeMethod(getMethod);
if(statusCode!= HttpStatus.SC_OK)
{
System.err.println("Method failed: "+getMethod.getStatusLine());
}
byte[] responseBody = getMethod.getResponseBody();
String response = new String(responseBody,"UTF-8");
JSONObject json = new JSONObject(response);
System.out.println("Total results = "+ json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount"));
JSONArray ja = json.getJSONObject("responseData").getJSONArray("results");
System.out.println("Results:");
for (int i = 0; i<ja.length();i++)
{
JSONObject j = ja.getJSONObject(i);
System.out.println(j.getString("titleNoFormatting"));
System.out.println(j.getString("url"));
System.out.println(j.get("content"));
}
}
catch(Exception e)
{
System.err.println("Something went wrong...");
e.printStackTrace();
}
System.out.println("--------------------------------------------");
}
public static void main(String args[])
{
try
{
new GoogleQuery();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}