通过Google的REST API使用Retrofit进行Google的自定义搜索

时间:2014-07-24 12:36:26

标签: android rest google-api retrofit

我制作了一款具有搜索功能的应用,该功能设置为从我自定义的Google搜索中搜索(使用自定义搜索服务)。这没有Java库,所以我使用Retrofit来请求使用REST API(https://developers.google.com/custom-search/json-api/v1/using_rest),但是我遇到了一个问题:

Retrofit工作正常,但请求始终返回400错误,其中包含以下信息: “domain”:“usageLimits”,“reason”:“keyInvalid”

我在请求中使用的API密钥是Google开发人员控制台中我的项目的Android应用程序密钥。我认为这不起作用,因为Retrofit不会让Google知道我是从我的应用程序发送请求的?

针对这种情况可能有哪些修复方法?

感谢。

编辑:我已经确认我的APK是使用正确的密钥签名的,而且我还是三次尝试 - 所有内容都检查了用于生成apikey的SHA1。我已经生成了一个新的api密钥大约3到4次,看看是否能修复它。

EDIT2:

我让它发挥作用了!

您没有制作Android API密钥(它不能用于此),您创建了一个浏览器API密钥,您可以在其中将所允许的引用设置为all(有潜在危险)。

您使用该API密钥请求使用Retrofit。我觉得谷歌应该注意到这一点:毫无疑问,许多人会认为Android应用程序? - > Android API密钥 - 但这只是Google为API创建库的情况。

1 个答案:

答案 0 :(得分:2)

听起来您只需将密钥作为查询参数传递到休息界面。

例如,如果您想在下面执行此GET命令

GET https://www.googleapis.com/customsearch/v1?key=INSERT_YOUR_API_KEY&cx=017576662512468239146:omuauf_lfve&q=lectures

然后你的界面将被声明为

public interface RestApi {
    GET ("/customsearch/v1")
    Response customSearch(@Query("key") String key, @Query("cx") String cx, @Query("q") String query);
}

然后你可以像这样执行调用

RestAdapter restAdapter = new RestAdapter.Builder()
  .setEndpoint("https://www.googleapis.com")
  .build();
RestApi restApi = restAdapter.create(RestApi.class)
restApi.customSearch("INSERT_YOUR_API_KEY", "017576662512468239146:omuauf_lfve", "lectures");

现在不要忘记用您在Google Dev Console中生成的密钥替换INSERT_YOUR_API_KEY。