[자바/Java]구글(Google) Gemini API 연동하기


장 건강부터 숙면까지 한 번에

🌙 3단계 슬립 케어

[자바/Java]구글(Google) Gemini API 연동하기

구글 Gemini API를 Java와 연동해보자

환경

윈도우 10

GOOGLE API KEY 발급

먼저 구글 제미나이 API 연동을 위해 구글 API키를 발급받아야함.

우선 ai.google.dev 로 접속해주자

[자바/Java]구글(Google) Gemini API 연동하기

Get API key in Google AI Studio 버튼 클릭

image 107

이용약관 동의 (필수만 체크함) 후 Continue 클릭

image 108

Get Api Key 클릭

image 109

Create API key 클릭

image 110

Create API key in new project 클릭


요즘 커뮤니티에서 슬슬 입소문 타는 2mg 꿀잠템

📍 품절되기 전에 확인

image 112

Copy 클릭

GOOGLE GEMINI API 가격 확인

image 113

api 가격은 ai.google.dev/pricing 에서 확인 가능하다

현재는 무료버전도 있음. 무료로 먼저 사용해보시기를 추천.

Java로 Api 연동 테스트 (Gemini 질문해보기)

image 114

ai.google.dev/tutorials/python_quickstart 공식 사이트에 api 연동 테스트에 대해서 자세히 설명되어 있다

하지만 파이썬 등 등 다른언어들은 있는데 자바는 안보여서, 파이썬을 참고해서 Java로 코드를 만들어보았다



public class GeminiApiCall {
    public static void main(String[] args) {
        try {
            // API endpoint URL
            URL url = new URL("https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=위에서 복사한 본인의 api Key");
            
            // Open a connection to the URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // Set the request method to POST
            connection.setRequestMethod("POST");
            
            // Set request headers
            connection.setRequestProperty("Content-Type", "application/json");
            
            // Enable output for sending data
            connection.setDoOutput(true);
            
            // Create JSON payload
            String payload = "{\"contents\":[{\"parts\":[{\"text\":\" what time is now????  (Please answer in Korean)  \"}]}]}";
            
            // Send JSON payload
            try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
                outputStream.writeBytes(payload);
            }
            
            // Get response code
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            
            // Read response
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                System.out.println("Response: " + response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

위 코드에서 import 및 api 키만 자신의 것으로 변경해주면 된다.

끝.


자고 일어나도 몸이 찌뿌둥하다면?

✨ 개운한 아침 루틴

Leave a Comment