If you program in Java and have never 'played' with GeminiAI, this article will be a great introductory guide, here I will present in a very simple way how to send requests to Gemini and return JSON, like a Rest API. ??
What am I using? ?
- Java 17
- Intelligence Community 2024.1.1
- Postman Card
- GeminiAI access key
LET'S START?
Start a simple project using the spring launcher, and include the following dependencies in your POM
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> <version>1.18.36</version> <scope>provided</scope> </dependency> <dependency> <groupid>com.fasterxml.jackson.core</groupid> <artifactid>jackson-databind</artifactid> <version>2.18.2</version> </dependency>
These dependencies will enable the use of Lombok, RestTemplate and ObjectMapper.
Lombok: to avoid repetitive codes (famous boilerplates) and to improve the readability of our code
RestTemplate: to make the http request to the GeminiAI API
ObjectMapper: to convert the Gemini api return into JSON
CONFIGURING THE RESTTEMPLATE
Let's configure the RestTemplate in our Java project, for this we create a class with the @Configuration annotation and the Bean to define it:
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
CREATING THE SERVICE
Let's create a service class to communicate with GeminiAI, this class will be responsible for all communication and processing of Gemini's response, and should look like this:
@Service public class TalkService { private final RestTemplate restTemplate; private final ObjectMapper objectMapper; @Value("${gemini.ai.api.url}") private String geminiApiUrl; @Value("${gemini.ai.api.key}") private String geminiApiKey; public TalkService(RestTemplate restTemplate, ObjectMapper objectMapper) { this.restTemplate = restTemplate; this.objectMapper = objectMapper; } public String callGeminiAI(TalkRequest input) { String url = geminiApiUrl + geminiApiKey; GeminiRequest request = new GeminiRequest(); GeminiRequest.Content content = new GeminiRequest.Content(); GeminiRequest.Part part = new GeminiRequest.Part(); part.setText(input.getChat()); content.setParts(Collections.singletonList(part)); request.setContents(Collections.singletonList(content)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<geminirequest> entity = new HttpEntity(request, headers); ResponseEntity<string> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); try { GeminiResponse geminiAIResponse = objectMapper.readValue(response.getBody(), GeminiResponse.class); if (geminiAIResponse.getCandidates() != null && !geminiAIResponse.getCandidates().isEmpty()) { GeminiResponse.Candidate candidate = geminiAIResponse.getCandidates().get(0); if (candidate.getContent() != null && candidate.getContent().getParts() != null && !candidate.getContent().getParts().isEmpty()) { return candidate.getContent().getParts().get(0).getText(); } } } catch (Exception e) { e.printStackTrace(); } return "Falha ao processar resposta da API"; } } </string></geminirequest>
Note that in this class we are using the POJO's GeminiRequest and GeminiResponse, below is the code to create them
GeminiRequest
@Getter @Setter @AllArgsConstructor @NoArgsConstructor public class GeminiRequest { private List<content> contents; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public static class Content { private List<part> parts; } @Getter @Setter @AllArgsConstructor @NoArgsConstructor public static class Part { private String text; } } </part></content>
GeminiResponse
@Getter @Setter @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class GeminiResponse { private List<candidate> candidates; private UsageMetadata usageMetadata; private String modelVersion; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public static class Candidate { private Content content; private String finishReason; private double avgLogprobs; } @Getter @Setter @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public static class Content { private List<part> parts; } @Getter @Setter @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public static class Part { private String text; } @Getter @Setter @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public static class UsageMetadata { private int promptTokenCount; private int candidatesTokenCount; private int totalTokenCount; } } </part></candidate>
CREATING A CONTROLLER
Now let's create a controller to listen to a Rest request and process it through our Service
@RestController @RequestMapping("v1") public class TalkController { private final TalkService talkService; @Autowired public TalkController(final TalkService talkService) { this.talkService = talkService; } @PostMapping("/chat-gemini") public TalkResponse talk(@RequestBody TalkRequest talkRequest) { TalkResponse response = new TalkResponse(); response.setResponse(talkService.callGeminiAI(talkRequest)); return response; } }
Our controller also has POJO's, check out their code below
TalkRequest
@Getter @Setter @AllArgsConstructor public class TalkRequest { private String chat; }
TalkResponse
@Getter @Setter @AllArgsConstructor @NoArgsConstructor public class TalkResponse { private String response; }
CONFIGURING VARIABLES IN PROPERTIES
You will need to inform the GeminiAI access endpoint and also your access key. I stored this information in the properties file, since we are talking about a simple test. Check the properties file with the necessary variables
spring.application.name=NOME_DA_SUA_APLICACAO gemini.ai.api.url=https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key= gemini.ai.api.key=SUA_CHAVE_DE_ACESSO
LET'S TEST IT??
We already have communication with GeminiAI, now we can test our application using postman, to do this start your application in Intellij and execute the request in postman as shown in the image below:
CONCLUSION ✔
The purpose of this article was to introduce Java programmers to connecting GeminiAI with a Java application, creating infinite new possibilities for use. I hope you enjoyed it, see you next time! ?
The above is the detailed content of Communicating JAVA with GeminiAI. For more information, please follow other related articles on the PHP Chinese website!

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
