[Java] Get images with Google Custom Search API

Things necessary

・ API key ・ Search engine ID Both can be obtained in the process of activating the Google Custom Search API.

Reference site

This article was helpful for getting API key and search engine ID. Get Google search results using Custom Search API

Click here for image search. Image collection using Google Custom Search API

Source code

Download 10 images from the search results. The save destination is specified in the download folder.

CustomSearch.java


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class CustomSearch {

	public static void main(String[] args) throws IOException {
		String key = "API key";
		String cx = "Search engine ID";
		String qry = "The character you want to search";
		String link = null;
		List<String> linkList = new ArrayList<String>();

		//Make a request to the Google Custom Search API
		URL url = new URL(
				"https://www.googleapis.com/customsearch/v1?key=" + key + "&cx=" + cx + "&q=" + qry
						+ "&searchType=image");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Accept", "application/json");
		BufferedReader br = new BufferedReader(new InputStreamReader(
				(conn.getInputStream())));

		//The response is json
		//Process to find URL from json
		String output;
		System.out.println("Output from Server .... \n");
		while ((output = br.readLine()) != null) {

			if (output.contains("\"link\": \"")) {

				link = output.substring(output.indexOf("\"link\": \"") + ("\"link\": \"").length(),
						output.indexOf("\","));
				System.out.println(link);
				linkList.add(link);
			}
		}
		conn.disconnect();

	    //The process of downloading an image from a URL.
		URL imageURL = null;
		HttpURLConnection urlConnection = null;

		for (int i = 0; i < 10; i++) {

			try {
				imageURL = new URL(linkList.get(i));

				urlConnection = (HttpURLConnection) imageURL.openConnection();
				//If true, allow redirects
				urlConnection.setInstanceFollowRedirects(true);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			//InputStream is a superclass of all classes that represent a byte input stream.
			InputStream in = null;

			try {
				in = urlConnection.getInputStream();
			} catch (IOException e) {
				e.printStackTrace();
			}

			byte[] buf = new byte[4096];
			int readSize;
			int total = 0;
			try {

				FileOutputStream fos = new FileOutputStream("C:\\Users\\user\\Downloads\\" + "test" + i + ".jpg ");

				//The read method is a value if there are no bytes to read because the stream has reached the end of the file-1 is returned.
				//The first byte read is element b[0]Stored in, the next byte is b[1]It is stored in, and so on.
				//The maximum number of bytes that can be read is the same as the length of b.
				while (((readSize = in.read(buf)) != -1)) {
					total = total + readSize;

					//Writes readSize bytes starting at offset position 0 of the specified byte array to this file output stream.
					fos.write(buf, 0, readSize);
				}
				fos.flush();
				fos.close();
				in.close();
			} catch (FileNotFoundException e) {
				System.out.println("File error");
			} catch (IOException e) {
				e.printStackTrace();
			}

			System.out.println("Size:" + total);
		}
	}
}

How it works

Throw the search character as a request to the API. A response is returned with json data. Find the URL of the image from the json data. Then connect to the URL and download! only this!

Recommended Posts

[Java] Get images with Google Custom Search API
Use Java 11 with Google Cloud Functions
Work with Google Sheets from Java
[Java] Get List / Map elements with Iterator
[Java] Get Json from URL and handle it with standard API (javax.script)
Introduction to algorithms with java --Search (depth-first search)
When calling API with java, javax.net.ssl.SSLHandshakeException occurs
Get Timestamp with Azure BlobStorage Java SDK
[Rails] Book search with Amazon PA API
[Java] New Yahoo! Product Search API Implementation
[Java8] Search the directory and get the file
[Java] Get the date with the LocalDateTime class
Introduction to algorithms with java --Search (breadth-first search)
[Android] [Java] Download images on GCS (Google Cloud Storage) with Stream using Glide
Interact with LINE Message API using Lambda (Java)
[Java] Create something like a product search API
Procedure for operating google spreadsheet with API (ruby)
Get block information with Hyperledger Iroha's Java SDK
How to use Java API with lambda expression
Try to get redmine API key with ruby
Get data with api created by curl command
Implement search function with Rakuten Books (DVD) API
Docker Container Operations with Docker-Client API for Java
[LeJOS] Get EV3 sensor value remotely with Java
Get along with Java containers in Cloud Run
Java Stream API
I tried using Google Cloud Vision API in Java
Experienced Java users get started with Android application development
Search by POST request with Azure Search + Java Apache HttpClient
Get Azure App Service for Java Configuration with System.getEnv ()
[Java] Get the date 10 days later with the Calendar class
[Java] Get the file path in the folder with List
[Java] I tried to implement Yahoo API product search
I want to get along with Map [Java beginner]
Set referrer limits on google vision api with hocalhost
Get started with serverless Java with the lightweight framework Micronaut!
Access Web API on Android with Get and process Json (Java for the time being)