Skip to content

Instantly share code, notes, and snippets.

@gantoin
Last active March 8, 2025 15:59
Show Gist options
  • Save gantoin/190684c344bb70e5c5f9f2339c7be6ed to your computer and use it in GitHub Desktop.
Save gantoin/190684c344bb70e5c5f9f2339c7be6ed to your computer and use it in GitHub Desktop.
🤖 How to use ChatGPT API in your Java application?

🤖 How to use ChatGPT API in your Java application?

tags: chatgpt, java, api

Hi guys 👋 I'm sure you enjoy using chat GPT to produce, optimise, or translate code from any programming language to Java.

Today I'll show you how to use OpenAI ChatGPT API with Java, it's pretty easy.

1. Register for an API key

First, you'll need to register for an API key by going to the OpenAI API page. Follow the instructions to create an account and obtain an API key.

2. Enter a credit card into your OpenAI account

OpenAI blocks the API calls for exceeded your current quota when you don't have any card registered in your account. So, you will need to configure one.

3. Implements code like:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class ChatGPT {
    public static void chatGPT(String text) throws Exception {
        String url = "https://api.openai.com/v1/completions";
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer YOUR-API-KEY");

        JSONObject data = new JSONObject();
        data.put("model", "text-davinci-003");
        data.put("prompt", text);
        data.put("max_tokens", 4000);
        data.put("temperature", 1.0);

        con.setDoOutput(true);
        con.getOutputStream().write(data.toString().getBytes());

        String output = new BufferedReader(new InputStreamReader(con.getInputStream())).lines()
                .reduce((a, b) -> a + b).get();

        System.out.println(new JSONObject(output).getJSONArray("choices").getJSONObject(0).getString("text"));
    }

    public static void main(String[] args) throws Exception {
        chatGPT("Hello, how are you?");
    }
}

It works!

src.main.java.ChatGPT


I'm doing great, thank you for asking. How about you?

Process finished with exit code 0

Resources used:

Copy link

ghost commented Oct 31, 2023

Don't construct the URL object using the constructor new URL(String), that's deprecated and would throw exceptions like "FileNotFoundException", "IOException" and so on. Please use this instead:

final URL url = new URI("URL_HERE").toURL();

This would fix the issues encountered by @mohammad-ayan-008 and @W1813

@NguyenTanDung-2004
Copy link

I dont know why
"Exception in thread "main" java.io.IOException: Server returned HTTP response code: 429 for URL: https://api.openai.com/v1/completions
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1997)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1589)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:224)
at testMaven.ChatGPT.chatGPT(ChatGPT.java:27)
at testMaven.ChatGPT.main(ChatGPT.java:34)
"

@jakefrey0
Copy link

Don't construct the URL object using the constructor new URL(String), that's deprecated and would throw exceptions like "FileNotFoundException", "IOException" and so on. Please use this instead:

final URL url = new URI("URL_HERE").toURL();

This would fix the issues encountered by @mohammad-ayan-008 and @W1813

It didn't fix my FileNotFoundException

@gantoin
Copy link
Author

gantoin commented Sep 14, 2024

Guys, you should use https://github.com/langchain4j/langchain4j, which is a more structured and feature-rich way to interact with the OpenAI API in Java. While directly plugging into the OpenAI API works, LangChain4j provides additional tools and abstractions like prompt templates, chains, and memory management, making it easier to build complex applications and manage interactions with large language models.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment