Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

AIzaSyAnm-ezJAgkyFr-Aml0aMdH6qcrv6HV2yw

AIzaSyBvG2jkYPaHBlEPtCi30s2BH6Vdo4FOWxk
-----------------
<script async src="https://cse.google.com/cse.js?cx=f4c33ce9d405b4ea5">
</script>
<div class="gcse-search"></div>

f4c33ce9d405b4ea5

e5cb4633dec594046

_-----------------------------------

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class GGSearch {

private static final String API_KEY = "AIzaSyAnm-ezJAgkyFr-


Aml0aMdH6qcrv6HV2yw";
private static final String CX = "f4c33ce9d405b4ea5";
private static final String API_URL =
"https://www.googleapis.com/customsearch/v1";

public static JSONObject searchImage(String query) throws IOException {


String parameters = "?q=" + URLEncoder.encode(query,
StandardCharsets.UTF_8)
+ "&cx=" + CX
+ "&searchType=image"
+ "&num=10"
+ "&key=" + API_KEY;

URL url = new URL(API_URL + parameters);


HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");

int responseCode = connection.getResponseCode();


if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException("Request failed. Response code: " +
responseCode);
}

try (InputStream inputStream = connection.getInputStream();


Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8)) {
String responseBody = scanner.useDelimiter("\\A").next();
return new JSONObject(responseBody);
}
}

public static void main(String[] args) {


try {
JSONObject result = searchImage("C:\\Users\\maiqu\\Desktop\\
images.jpg");

JSONArray items = result.getJSONArray("items");

for (int i = 0; i < items.length(); i++) {


JSONObject item = items.getJSONObject(i);
String thumbnailUrl =
item.getJSONObject("image").getString("thumbnailLink");
String contentUrl = item.getString("link");

System.out.println("Thumbnail URL: " + thumbnailUrl);


System.out.println("Content URL: " + contentUrl);
System.out.println();
}

} catch (IOException e) {
e.printStackTrace();
}
}
}

You might also like