Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class AlbumArtGrabber {
- // ключ API
- public final static String API_KEY = "******";
- // ID поисковой системы
- public final static String SEARCH_ENGINE = "*********";
- private final static String ENCODING = "UTF-8";
- // полный URL для поискового запроса
- private final static String GET_URL = "https://www.googleapis.com/customsearch/v1?key="
- + API_KEY + "&cx=" + SEARCH_ENGINE + "&q=";
- public static List<URL> doGoogleSearch(final String query, int page) {
- if (query == null || query.trim().isEmpty() || page < 1) {
- throw new IllegalArgumentException(
- "Ошибка: заданы некорректные аргументы.");
- }
- List<URL> result = new ArrayList<URL>();
- // заменяем все пробелы в поисковом запросе, если есть
- String searchQuery = query.replaceAll(" ", "+");
- System.out.println("Поиск начался.");
- try {
- // номер страцы результатов поиска Google
- String start = "&start=" + String.valueOf(page);
- // небходимо закодировать UTF-8 строку
- searchQuery = URLEncoder.encode(searchQuery, ENCODING);
- URL url = new URL(GET_URL + searchQuery + start + "&alt=json&");
- // выполняем GET запрос и получаем список ссылок
- // из результатов поиска
- result.addAll(getListOfUrlsFormGoogleResponse(url));
- System.out.println("Поиск завершен");
- } catch (Exception e) {
- System.err.println("Во время поиска произошла ошибка: "
- + e.getMessage());
- }
- return result;
- }
- private static List<URL> getListOfUrlsFormGoogleResponse(final URL url)
- throws ProtocolException, IOException {
- List<URL> result = new ArrayList<URL>();
- // создаем соединение
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- // заголовоки GET запроса
- conn.setRequestMethod("GET");
- conn.setRequestProperty("Accept", "application/json");
- BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
- System.out.println("Строка поискового запроса: " + url.toString());
- System.out.println("Ответ от сервера: ");
- // ответ от сервера
- // в ответе содержится различная информация, однако нам необходимо
- // получить
- // только URL
- String output;
- while ((output = br.readLine()) != null) {
- System.out.println(output);
- final String PARAM = ""link": "";
- // берем из ответа только ссылку и добавляем ее в результат
- if (output.contains(PARAM)) {
- String link = output.substring(
- output.indexOf(PARAM) + (PARAM).length(),
- output.indexOf("","));
- result.add(new URL(link));
- }
- }
- //закрываем сетевое соединение
- conn.disconnect();
- return result;
- }}
- {
- "kind": "customsearch#result",
- "title": "Astronomy Picture of the Day",
- "htmlTitle": "Astronomy Picture of the Day",
- "link": "https://apod.nasa.gov/apod/astropix.html",
- "displayLink": "apod.nasa.gov",
- "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 ...",
- "htmlSnippet": "Explanation: Normally faint and elusive, the Jellyfish Nebula is caught in this u003cbru003enalluring telescopic u003cbu003eimageu003c/bu003e. Centered in the scene it'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 ...",
- "cacheId": "87TgjKwQQIYJ",
- "formattedUrl": "https://apod.nasa.gov/apod/astropix.html",
- "htmlFormattedUrl": "https://apod.nasa.gov/apod/astropix.html",
- "pagemap": {
- "cse_thumbnail": [
- {
- "width": "276",
- "height": "182",
- "src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRe-lmsRxetMUTlcce6X6Kk2pM7o20HVyLAMHK_qwyQcJCNiwcmYJQ0yZE"
- }
- ],
- "metatags": [
- {
- "orgcode": "661",
- "rno": "phillip.a.newman",
- "content-owner": "Jerry.T.Bonnell.1",
- "webmaster": "Stephen.F.Fantasia.1",
- "viewport": "width=device-width, initial-scale=1"
- }
- ],
- "cse_image": [
- {
- "src": "https://apod.nasa.gov/apod/image/1803/IC443_HaRGB1024.jpg"
- }
- ]
- }
- },
- Поиск завершен
- Список ссылок из результатов поиска:
- https://vk.com/kartinka_da
- https://translate.yandex.ru/ocr
- https://www.google.com/imghp?hl=ru
- http://bipbap.ru/category/krasivye-kartinki
- http://tilda.education/articles-images-for-social
- 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/
- http://www.astronet.ru/db/apod.html
- https://apod.nasa.gov/apod/astropix.html
- https://www.livejournal.com/support/faq/6.html
- http://chandra.harvard.edu/photo/2017/dark/
- Process finished with exit code 0
- "src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRe-lmsRxetMUTlcce6X6Kk2pM7o20HVyLAMHK_qwyQcJCNiwcmYJQ0yZE"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement