我正在制作一个 JavaFX 应用程序,我需要为搜索查询获取图像。您可以通过 google-api-services-customsearch 通过 java 搜索 google,但搜索需要访问令牌和 google api 中的应用程序。
我在 google apis 中创建了一个应用程序,创建时GoogleCredential指定了客户端 ID(其长度为 72 个字符),创建时Customsearch.Builder指定了应用程序的名称appname-143932,但在尝试完成请求后我收到授权错误。
{
"code" : 401,
"errors" : [ {
"domain" : "global",
"location" : "Authorization",
"locationType" : "header",
"message" : "Invalid Credentials",
"reason" : "authError"
} ],
"message" : "Invalid Credentials"
}
完整代码(科特林):
val credential = GoogleCredential().setAccessToken(token)
val customsearch = Customsearch.Builder(NetHttpTransport(), JacksonFactory(), credential)
.setApplicationName(appName)
.build()
val list = customsearch.cse().list("image name")
list.searchType = "image"
val search = list.execute()
val items = search.items
items
.forEach {
println(it.displayLink)
}
事实证明,对于常规搜索,不需要授权和获取任何令牌,但您需要注册项目和用户搜索系统。
下面是一个简单的图像搜索类的示例。