Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {
- "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)
- }
- /**
- * Класс для поиска изображений через Google Custom API
- *
- * 1) Создать проект с именем {@param projectName} на странице https://console.developers.google.com/apis/
- * 2) Включить Custom Search API и запомнить API key {@param apiKey}
- * 3) Создать пользовательский поиск https://cse.google.com/cse/all, запомнить id поисковой системы {@param cx},
- * при редактировании включить поиск изображений по умолчанию он выключен
- */
- class GoogleImageSearch(val apiKey: String, val cx: String, projectName: String) {
- private val builder = Customsearch.Builder(NetHttpTransport(), JacksonFactory(), null)
- private val customsearch: Customsearch
- private val cse: Customsearch.Cse
- init {
- builder.applicationName = projectName
- customsearch = builder.build()
- cse = customsearch.cse()
- }
- /**
- * @param query - Поисковый запрос
- * @param imageSize - размер картинки
- * @param index - начальный индекс результатов
- * @return результаты запроса
- */
- fun search(query: String, imageSize: String = "medium", index: Long = 1): MutableList<Result>? {
- val list = cse.list(query)
- list.key = apiKey
- list.cx = cx
- list.searchType = "image"
- list.imgSize = imageSize
- list.start = index
- val search = list.execute()
- return search.items
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement