Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2018
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.66 KB | None | 0 0
  1. public class AlbumArtGrabber {
  2.  
  3. // ключ API
  4. public final static String API_KEY = "******";
  5. // ID поисковой системы
  6. public final static String SEARCH_ENGINE = "*********";
  7.  
  8. private final static String ENCODING = "UTF-8";
  9. // полный URL для поискового запроса
  10. private final static String GET_URL = "https://www.googleapis.com/customsearch/v1?key="
  11. + API_KEY + "&cx=" + SEARCH_ENGINE + "&q=";
  12.  
  13.  
  14. public static List<URL> doGoogleSearch(final String query, int page) {
  15.  
  16. if (query == null || query.trim().isEmpty() || page < 1) {
  17. throw new IllegalArgumentException(
  18. "Ошибка: заданы некорректные аргументы.");
  19. }
  20.  
  21. List<URL> result = new ArrayList<URL>();
  22.  
  23. // заменяем все пробелы в поисковом запросе, если есть
  24. String searchQuery = query.replaceAll(" ", "+");
  25.  
  26. System.out.println("Поиск начался.");
  27.  
  28. try {
  29. // номер страцы результатов поиска Google
  30. String start = "&start=" + String.valueOf(page);
  31. // небходимо закодировать UTF-8 строку
  32. searchQuery = URLEncoder.encode(searchQuery, ENCODING);
  33.  
  34. URL url = new URL(GET_URL + searchQuery + start + "&alt=json&");
  35. // выполняем GET запрос и получаем список ссылок
  36. // из результатов поиска
  37. result.addAll(getListOfUrlsFormGoogleResponse(url));
  38.  
  39. System.out.println("Поиск завершен");
  40.  
  41. } catch (Exception e) {
  42. System.err.println("Во время поиска произошла ошибка: "
  43. + e.getMessage());
  44. }
  45.  
  46. return result;
  47. }
  48.  
  49.  
  50. private static List<URL> getListOfUrlsFormGoogleResponse(final URL url)
  51. throws ProtocolException, IOException {
  52.  
  53. List<URL> result = new ArrayList<URL>();
  54.  
  55. // создаем соединение
  56. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  57.  
  58. // заголовоки GET запроса
  59. conn.setRequestMethod("GET");
  60. conn.setRequestProperty("Accept", "application/json");
  61.  
  62. BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
  63.  
  64. System.out.println("Строка поискового запроса: " + url.toString());
  65. System.out.println("Ответ от сервера: ");
  66.  
  67. // ответ от сервера
  68. // в ответе содержится различная информация, однако нам необходимо
  69. // получить
  70. // только URL
  71.  
  72. String output;
  73.  
  74. while ((output = br.readLine()) != null) {
  75.  
  76. System.out.println(output);
  77.  
  78. final String PARAM = ""link": "";
  79.  
  80. // берем из ответа только ссылку и добавляем ее в результат
  81. if (output.contains(PARAM)) {
  82. String link = output.substring(
  83. output.indexOf(PARAM) + (PARAM).length(),
  84. output.indexOf("","));
  85.  
  86. result.add(new URL(link));
  87. }
  88. }
  89.  
  90. //закрываем сетевое соединение
  91. conn.disconnect();
  92.  
  93. return result;
  94. }}
  95.  
  96. {
  97. "kind": "customsearch#result",
  98. "title": "Astronomy Picture of the Day",
  99. "htmlTitle": "Astronomy Picture of the Day",
  100. "link": "https://apod.nasa.gov/apod/astropix.html",
  101. "displayLink": "apod.nasa.gov",
  102. "snippet": "Explanation: Normally faint and elusive, the Jellyfish Nebula is caught in this nalluring telescopic image. Centered in the scene it's anchored right and left by ntwo bright stars, Mu and Eta Geminorum, at the foot of the celestial twin. The nJellyfish Nebula is the brighter arcing ridge of emission with dangling tentacles. nIn fact, the ...",
  103. "htmlSnippet": "Explanation: Normally faint and elusive, the Jellyfish Nebula is caught in this u003cbru003enalluring telescopic u003cbu003eimageu003c/bu003e. Centered in the scene it&#39;s anchored right and left by u003cbru003entwo bright stars, Mu and Eta Geminorum, at the foot of the celestial twin. The u003cbru003enJellyfish Nebula is the brighter arcing ridge of emission with dangling tentacles. u003cbru003enIn fact, the&nbsp;...",
  104. "cacheId": "87TgjKwQQIYJ",
  105. "formattedUrl": "https://apod.nasa.gov/apod/astropix.html",
  106. "htmlFormattedUrl": "https://apod.nasa.gov/apod/astropix.html",
  107. "pagemap": {
  108. "cse_thumbnail": [
  109. {
  110. "width": "276",
  111. "height": "182",
  112. "src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRe-lmsRxetMUTlcce6X6Kk2pM7o20HVyLAMHK_qwyQcJCNiwcmYJQ0yZE"
  113. }
  114. ],
  115. "metatags": [
  116. {
  117. "orgcode": "661",
  118. "rno": "phillip.a.newman",
  119. "content-owner": "Jerry.T.Bonnell.1",
  120. "webmaster": "Stephen.F.Fantasia.1",
  121. "viewport": "width=device-width, initial-scale=1"
  122. }
  123. ],
  124. "cse_image": [
  125. {
  126. "src": "https://apod.nasa.gov/apod/image/1803/IC443_HaRGB1024.jpg"
  127. }
  128. ]
  129. }
  130. },
  131.  
  132. Поиск завершен
  133. Список ссылок из результатов поиска:
  134. https://vk.com/kartinka_da
  135. https://translate.yandex.ru/ocr
  136. https://www.google.com/imghp?hl=ru
  137. http://bipbap.ru/category/krasivye-kartinki
  138. http://tilda.education/articles-images-for-social
  139. https://www.1zoom.ru/%D0%A0%D0%B0%D0%B7%D0%BD%D0%BE%D0%B5/%D0%9B%D1%8E%D0%B1%D0%BE%D0%B2%D1%8C/t2/1/
  140. http://www.astronet.ru/db/apod.html
  141. https://apod.nasa.gov/apod/astropix.html
  142. https://www.livejournal.com/support/faq/6.html
  143. http://chandra.harvard.edu/photo/2017/dark/
  144.  
  145. Process finished with exit code 0
  146.  
  147. "src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRe-lmsRxetMUTlcce6X6Kk2pM7o20HVyLAMHK_qwyQcJCNiwcmYJQ0yZE"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement