ChatGPT API in JAVA | (simple & easy)
ฝัง
- เผยแพร่เมื่อ 9 ก.พ. 2025
- ChatGPT API in JAVA | (simple & easy)
In today's video, I will be showing you how to use ChatGPT's API in Java.
► Code Used:
● Check the pinned comment.
► ChatGPT API KEY:
● platform.opena...
► Software Used:
● IntelliJ IDEA: www.jetbrains....
► Helpful Learning Sites:
● Codecademy: www.codecademy...
● freeCodeCamp: www.freecodeca...
► Song Used:
● One More Time: • [FREE] Lofi Type Beat ...
► Support or Follow me:
● Join our Discord: / discord
● GitHub: github.com/Min...
(updated june 2023)
API KEY: no longer works! get your own! link in desc!
Code Used:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
System.out.println(chatGPT("hello, how are you?"));
// Prints out a response to the question.
}
public static String chatGPT(String message) {
String url = "api.openai.com/v1/chat/completions";
String apiKey = "KEY GOES HERE!!!!!!!!!!!"; // API key goes here
String model = "gpt-3.5-turbo"; // current model of chatgpt api
try {
// Create the HTTP POST request
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Bearer " + apiKey);
con.setRequestProperty("Content-Type", "application/json");
// Build the request body
String body = "{\"model\": \"" + model + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + message + "\"}]}";
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(body);
writer.flush();
writer.close();
// Get the response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// returns the extracted contents of the response.
return extractContentFromResponse(response.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// This method extracts the response expected from chatgpt and returns it.
public static String extractContentFromResponse(String response) {
int startMarker = response.indexOf("content")+11; // Marker for where the content starts.
int endMarker = response.indexOf("\"", startMarker); // Marker for where the content ends.
return response.substring(startMarker, endMarker); // Returns the substring containing only the response.
}
}
nice
Ran the above code in InteliJ and got ssl handshake exception. Any ideas on how to get this to work?
1. Try running code locally on your computer if you aren't already.
2. make sure you are connected to wifi or ethernet (obv)
3. make sure ur code is the same as mine exactly!
4. make sure you use your own api-key!
if you still are having trouble, maybe ask chatgpt how to fix itself lol
@@mintype I got it to work, just needed to download the ssl certificate from the api url and to add it to the project in InteliJ, Thanks
5head@@mintype
join the discord! -> discord.gg/hhGu6mV5wm
I get an "Server returned HTTP response code: 429" Error. I believer the BufferedReader in is what's causing the issue. Any ideas on what might be going wrong?
Check your api key is valid not expired and works. Also check how much free trial money you have left if you are in the free trial. (Other people have had the same issue before)
@@mintype Even I am getting the same error any idea I doing a poc for a very important project can anyone help me please .
thank you a lot for this video!
works for me. ty bro
Good to hear
Hey is it free?
YOU SHOULD MAKE MORE VIDEOS BRO
On what
on this topic ofc@@mintype
Hey, how could I get the Java codes? You mentioned that check description, but I failed to find it...
Heres the code (updated):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
System.out.println(chatGPT("hello, how are you?"));
// Prints out a response to the question.
}
public static String chatGPT(String message) {
String url = "api.openai.com/v1/chat/completions";
String apiKey = "KEY GOES HERE!!!!!!!!!!!"; // API key goes here
String model = "gpt-3.5-turbo"; // current model of chatgpt api
try {
// Create the HTTP POST request
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Bearer " + apiKey);
con.setRequestProperty("Content-Type", "application/json");
// Build the request body
String body = "{\"model\": \"" + model + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + message + "\"}]}";
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(body);
writer.flush();
writer.close();
// Get the response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// returns the extracted contents of the response.
return extractContentFromResponse(response.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// This method extracts the response expected from chatgpt and returns it.
public static String extractContentFromResponse(String response) {
int startMarker = response.indexOf("content")+11; // Marker for where the content starts.
int endMarker = response.indexOf("\"", startMarker); // Marker for where the content ends.
return response.substring(startMarker, endMarker); // Returns the substring containing only the response.
}
}
@@mintype hello
@@supercodingandmath2826 can you share github repo address?
bro i have getting 3 errors near regex: beginIndex: it's saying : is not corroct in vs code
Could you please make a video explaining how to use Ollama API with java?
Ollama is a command-line based program that runs locally and runs models like llama2, llama3, etc...
ill see about that!
@@mintype Thank you so much!
I've just finished recording the video! So expect it to be released soon!
@@mintype OMG thank you so much!!
im done editing and working on thumbnail now :)
This doesnt work for me
can you create for google gemini ?
when I ask for a java program it is not giving the complete output. Could you help me in this?
Prompt the API with "continue" after if it is incomplete.
Yes I use my api key but it why the link cgatgpt link is not working
How do I fix error code 429? noone else has my api key
Either you have reached the rate limit OR you don't have enough funds in your OpenAI account.
@@mintype i have never used any api key and i have enough funds in my account
Ca we do the same thing in VS COde?
Yes, it will work in VS Code, just make sure to use all the right imports!
what is String Model Used to
gpt-3.5-turbo
I don't know why it always refuses the connection when i try to execute it
Check if your API free trial has expired yet. Many people get the same issue and don't realize their trial has expired.
can you share github repo address?
Theres no repo for this but there is code in the pinned comment
hello bro can u plz make more video's like this only diffrent i love this type of consept's
learn how to spell
free account can't use api :(
Requires GPT-4, because when reading an error message after asking, getting insufficient credits
It means your openAI account doesn’t have any funds/money left
This doesn't work for me. Did open ai change anything?
same bro please tell if you found any update/solutions
i got server 429 error for first time why is it happening
Check your api key is working and valid. Make sure it is not expired if it is a free trial.
where is the code
Its the pinned comment.
I can't get the code to work. Error 429. I have created another user with another key
Error 429 may happen to you if you send too many requests in a short period of time.
@@mintype with a new user and new key if i do the first request the code is it. Is possible any change with free counter politic?
@@mintype Bro even showing 429 for first time call 🤔
@@mintypein first request this happens
Does anyone solve this problem? I'm having the same issue. I'm using Eclipse IDE
I think API keys are expired now, so we must pay to run the code?
Plz. reply me as fast as you can, i must finish my project in next two weeks
Yeah you have to pay but its really cheap