LoginSignup
1
2

More than 3 years have passed since last update.

【Java】Google Custom Search APIで画像を取得する

Last updated at Posted at 2020-07-24

必要なもの

・APIキー
・検索エンジンID
どちらもGoogle Custom Search APIを有効化する過程で取得できます。

参考サイト

APIキーと検索エンジンID取得はこちらの記事が参考になりました。
Custom Search APIを使ってGoogle検索結果を取得する

画像検索についてはこちら。
Google Custom Search APIを使って画像収集

ソースコード

検索結果から画像を10枚ダウンロードします。
保存先はダウンロードフォルダに指定しました。

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キー";
        String cx = "検索エンジン ID";
        String qry = "検索したい文字";
        String link = null;
        List<String> linkList = new ArrayList<String>();

        //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())));

        //レスポンスはjson
        //jsonからURLを探し出す処理
        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();

        //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();
                //  trueならリダイレクトを認める
                urlConnection.setInstanceFollowRedirects(true);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // InputStreamはバイト入力ストリームを表現するすべてのクラスのスーパー・クラスです。
            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");

                //readメソッドはストリームがファイルの終わりに達したために読み込むバイトがない場合は値-1が返されます。
                // 最初に読み込まれたバイトは要素b[0]に格納され、次のバイトはb[1]に格納され、それ以降も同様に続きます。
                //読み込まれるバイト数の上限はbの長さと同じです。
                while (((readSize = in.read(buf)) != -1)) {
                    total = total + readSize;

                    //指定されたバイト配列のオフセット位置0から始まるreadSizeバイトをこのファイル出力ストリームに書き込みます。
                    fos.write(buf, 0, readSize);
                }
                fos.flush();
                fos.close();
                in.close();
            } catch (FileNotFoundException e) {
                System.out.println("ファイルエラー");
            } catch (IOException e) {
                e.printStackTrace();
            }

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

どんな仕組みなの

検索文字をリクエストとしてAPIに投げる。
jsonデータでレスポンスが返ってくる。
そのjsonデータから画像のURLを探す。
そしてURLに接続してダウンロード!
これだけ!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2