DEVSAIO

Call AI models from Java with HttpClient

Use Java 11+'s built-in HttpClient to send chat requests to any model through DEVSAIO.

DEVSAIO team · 1 min read
Share on X

Java 11 and newer ship java.net.http.HttpClient, so you don't need extra dependencies for a basic client. This example uses Jackson for JSON, which most projects already have.

java
import com.fasterxml.jackson.databind.*;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.*;

public class Ai {
  private static final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(20)).build();
  private static final ObjectMapper json = new ObjectMapper();

  public static String chat(String model, String prompt) throws Exception {
    Map<String, Object> body = Map.of(
      "model", model,
      "max_tokens", 800,
      "messages", List.of(Map.of("role", "user", "content", prompt))
    );
    HttpRequest req = HttpRequest.newBuilder(URI.create("https://devsaio.lol/v1/chat/completions"))
      .timeout(Duration.ofSeconds(120))
      .header("Authorization", "Bearer " + System.getenv("DEVSAIO_API_KEY"))
      .header("Content-Type", "application/json")
      .POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body)))
      .build();
    HttpResponse<String> res = http.send(req, HttpResponse.BodyHandlers.ofString());
    JsonNode root = json.readTree(res.body());
    if (res.statusCode() != 200) throw new RuntimeException(root.path("error").path("message").asText("AI error " + res.statusCode()));
    return root.path("choices").get(0).path("message").path("content").asText();
  }

  public static void main(String[] args) throws Exception {
    System.out.println(chat("claude-sonnet-4-6", "Give me 3 tips for writing clean Java."));
  }
}

Spring Boot

Spring AI's OpenAI integration accepts a custom base URL in configuration (spring.ai.openai.base-url). Point it at https://devsaio.lol or https://devsaio.lol/v1 depending on whether your Spring AI version appends /v1 itself, set the API key and choose a model in spring.ai.openai.chat.options.model.

Try it with one API key

Claude, GPT, Gemini, DeepSeek, image and video models through one OpenAI- and Anthropic-compatible endpoint. Prepaid, pay only for what you use.

Keep reading