4

我想让用户在我的应用程序中输入一个关键字,然后在谷歌搜索这个关键字,对结果执行一些逻辑并向用户显示最终结论。

这可能吗?如何从我的应用程序在 google 上执行搜索?回复的格式是什么?如果有人对此有一些代码示例,将不胜感激。

谢谢,

4

1 回答 1

10

对 Google AJAX的RESTful 搜索请求会返回JSON格式的响应。

您可以使用ASIHTTPRequest发出请求,并使用json-framework在 iPhone 上解析 JSON 格式的响应。

例如,要创建并提交基于 Google AJAX 页面上的示例的搜索请求,您可以使用 ASIHTTPRequest 的-requestWithURL-startSynchronous方法:

NSURL *searchURL = [NSURL URLWithString:@"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton"];
ASIHTTPRequest *googleRequest = [ASIHTTPRequest requestWithURL:searchURL];
[googleRequest addRequestHeader:@"Referer" value:[self deviceIPAddress]]; 
[googleRequest startSynchronous];

NSURL您将根据搜索词构建实例,转义请求参数。

如果我完全按照 Google 的示例进行操作,我还会在此 URL 中添加一个 API 密钥。Google 要求您使用 API 密钥进行搜索,但显然这不是必需的。您可以在此处注册 API 密钥。

还有异步请求方法,在 ASIHTTPRequest 文档中有详细说明。在发出搜索请求时,您将使用它们来防止 iPhone UI 被捆绑。

获得 Google 的 JSON 格式响应后,您可以使用 json-frameworkSBJSON解析器对象将响应解析为NSDictionary对象:

NSError *requestError = [googleRequest error];
if (!requestError) {
    SBJSON *jsonParser = [[SBJSON alloc] init];
    NSString *googleResponse = [googleRequest responseString];
    NSDictionary *searchResults = [jsonParser objectWithString:googleResponse error:nil];
    [jsonParser release];
}

您还应该在请求标头中指定引用 IP 地址,在这种情况下将是 iPhone 的本地 IP 地址,例如:

- (NSString *) deviceIPAddress {
    char iphoneIP[255];
    strcpy(iphoneIP,"127.0.0.1"); // if everything fails
    NSHost *myHost = [NSHost currentHost];
    if (myHost) {
        NSString *address = [myHost address];    
        if (address)
            strcpy(iphoneIP, [address cStringUsingEncoding:NSUTF8StringEncoding]);
    }
    return [NSString stringWithFormat:@"%s",iphoneIP]; 
}
于 2010-04-25T09:20:09.537 回答