我有一个我在SO上找到的程序,允许用户输入查询并使用谷歌搜索任何输入的内容。然后该程序返回Google提供的前4个结果。这是代码:
public class TestGoogleSea {
public static void main(String[] args) throws IOException {
String address = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String query = "who was the 19th president of america";
String charset = "UTF-8";
URL url = new URL(address + URLEncoder.encode(query, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
int total = results.getResponseData().getResults().size();
System.out.println("total: "+total);
// Show title and URL of each results
for(int i=0; i<=total-1; i++){
System.out.println("Title: " + results.getResponseData().getResults().get(I).getTitle());
System.out.println("URL: " + results.getResponseData().getResults().get(I).getUrl() + "\n");
}
}
}
class GoogleResults{
private ResponseData responseData;
public ResponseData getResponseData() { return responseData; }
public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
public String toString() { return "ResponseData[" + responseData + "]"; }
static class ResponseData {
private List<Result> results;
public List<Result> getResults() { return results; }
public void setResults(List<Result> results) { this.results = results; }
public String toString() { return "Results[" + results + "]"; }
}
static class Result {
private String url;
private String title;
public String getUrl() { return url; }
public String getTitle() { return title; }
public void setUrl(String url) { this.url = url; }
public void setTitle(String title) { this.title = title; }
public String toString() { return "Result[url:" + url +", title:" + title + "]"; }
}
}
对于这个特定情况,(当查询是&#34;谁是美国第19任总统&#34;)时,输出是这样的:
Total: 4
Title: Rutherford B. Hayes - Wikipedia, the free encyclopedia
URL: http://en.wikipedia.org/wiki/Rutherford_B._Hayes
Title: List of <b>Presidents</b> of the United States - Wikipedia, the free <b>...</b>
URL: http://en.wikipedia.org/wiki/List_of_Presidents_of_the_United_States
Title: Rutherford B. Hayes | The White House
URL: http://www.whitehouse.gov/about/presidents/rutherfordbhayes
Title: <b>American President</b>: Rutherford Birchard Hayes - Miller Center
URL: http://millercenter.org/president/hayes
现在,如果你真的在寻找&#34;谁是美国第19任总统&#34;在Google上,除了网站列表之外,你还可以看到Rutherford B. Hayes的图片和他的名字以及更多关于Rutherford B. Hayes&#34;的内容。我要问的是,无论如何我都能得到这些信息,谷歌从维基百科得到的海耶斯的简短描述最好是作为一个字符串,或者由于Gson的限制而无法实现?