Connecting to GigaChat API in Java: Step by Step Guide
Hi all! In this article, I'll walk you through how to connect to the GigaChat API in IntelliJ IDEA in Java and set up a secure connection using SSL certificates to receive responses from GigaChat in your application.
1. What is GigaChat and why is it needed?
The GigaChat API is an interface for integrating an AI system designed to conduct conversations and assist with text generation. It can be used to create interactive applications such as chatbots, help desk systems, and more complex analytical tools that require language processing.
GigaChat itself has detailed documentation on API integration -> Installation | Developer Documentation however, I decided that a step-by-step personal example might be of interest to the community and perhaps save someone a little time when setting up.
2. Setting up the environment
To work with the GigaChat API you will need Java, as well as a client for HTTP requests, e.g. OkHttp
. Below is a list of dependencies and some basic settings.
Dependencies
Let's add OkHttp to the project to send HTTP requests. If you are using Gradle, add to build.gradle
:
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
}
3. Obtaining SSL certificates
Since the GigaChat API requires a secure connection, SSL certificates must be configured. Obtain the root and subordinate certificates (CA Certificates) according to the documentation and save them in the project folder. I posted them on my src/main/resources/certs
.
4. Class for connecting to the API
Below is the code that creates a request to the GigaChat API using OkHttpClient
with SSL certificate settings.
Code for GigaChatDialog
import okhttp3.*;
import javax.net.ssl.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
public class GigaChatDialog {
private static final String API_URL = "https://gigachat.devices.sberbank.ru/api/v1/chat/completions";
private static final String CERT_PATH = "src/main/resources/certs/russian_trusted_sub_ca.cer";
private static final String ACCESS_TOKEN = "токен_доступа";
private OkHttpClient client;
public GigaChatDialog() {
try {
this.client = createClient();
} catch (Exception e) {
e.printStackTrace();
}
}
private OkHttpClient createClient() throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream certInput = new FileInputStream(CERT_PATH);
X509Certificate caCert = (X509Certificate) cf.generateCertificate(certInput);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("caCert", caCert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
return new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) tmf.getTrustManagers()[0])
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
}
public String getResponse(String message) {
String jsonPayload = "{ \"model\": \"GigaChat\", \"messages\": [{ \"role\": \"user\", \"content\": \"" + message + "\" }], \"stream\": false }";
RequestBody body = RequestBody.create(jsonPayload, MediaType.get("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(API_URL)
.post(body)
.addHeader("Authorization", "Bearer " + ACCESS_TOKEN)
.addHeader("Content-Type", "application/json")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
return new String(response.body().bytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
What does this code do?
Uploads a certificate: Uses
TrustManagerFactory
to download the root certificate.Configures SSLContext: Configures the OkHttp client to work with a certificate and SSLContext.
Generates a request: Creates a JSON payload with the request text and sends it to the server.
Processes the response: Receives the response and returns it as a string in
UTF-8
to avoid encoding problems.
5. What kind of beast is AccessToken and where to get it
The GigaChat API doc states that an AccessToken is required for interaction; its lifetime is 30 minutes. You can get it in several ways:
forward curl as written in official documentation or there is a small method in Phyton, but curl did not work for me, so I went my own way and wrote a small method in java that receives a token, here are the key points
// Кодирование client_id и client_secret в формате Base64
String authKey = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8));
// Создание тела запроса для POST
RequestBody formBody = new FormBody.Builder()
.add("scope", "GIGACHAT_API_PERS")
.build();
// Создание запроса
Request request = new Request.Builder()
.url(url)
.post(formBody)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Accept", "application/json")
.addHeader("RqUID", "хххххххх-хххх-хххх-хххх-хххххххххххх") // Замените на уникальный идентификатор запроса
.addHeader("Authorization", "Basic " + authKey)
.build();
// Создание OkHttpClient с SSL-сертификатом
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) tmf.getTrustManagers()[0])
.build();
// Выполнение запроса
try (Response response = client.newCall(request).execute()) {
// Обработка ответа
if (response.isSuccessful() && response.body() != null) {
System.out.println("Access Token: " + response.body().string());
} else {
System.out.println("Response body: " + (response.body() != null ? response.body().string() : "No response body"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
I would like to note here that RqUID – a required field, without it I got an error of incorrect request format.
6. Example of use
Now let's use our class GigaChatDialog
to get a response from the GigaChat API.
public static void main(String[] args) {
GigaChatDialog chatDialog = new GigaChatDialog();
String response = chatDialog.getResponse("Привет, GigaChat! Как дела?");
System.out.println("GigaChat: " + response);
}
We will receive the answer in the following format:
7. Problems I encountered when connecting
RQUID – required in request headers
401 Unauthorized: Check if the access token is specified correctly.
SSLHandshakeException: Make sure that the certificates are loaded correctly and the paths to them are correct.
Instead of a conclusion
Now you know how to connect a Java application to the GigaChat API and how to configure the client to work with SSL certificates. I hope this article was useful and will help you use AI in your projects! Share your thoughts and questions in the comments – it will be interesting to discuss!