how can I call an API endpoint at runtime? I'm new to this business I have an endpoint in my spring project that saves products (a json file that is in the project) to MongoDB I need products to be saved before the user uses my application
Asked
Active
Viewed 553 times
-1
-
Read file on project start-up and save in db with `ProductService`? Why even call endpoint, if it's part of your project? Add some more details, it's not clear what you want to achieve. – Chaosfire Mar 13 '22 at 17:22
-
@Chaosfire , you understood correctly, this endpoint is necessary to add products manually, but due to the circumstances, we are forced to do such a trick (hard code) And. I don't understand how to call the endpoint at runtime. – Александр Хворостенко Mar 13 '22 at 21:51
1 Answers
0
You need a client to make the request at the appropriate time. There are lots of options, so i will list only a few:
- Java provided functionality. Not really recommended, unless you want to learn the basics. You can read here.
- Apache HttpComponents. A simple get request example:
ObjectMapper mapper = new ObjectMapper();
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet("https://your.host/endpoint");
HttpResponse httpResponse = client.execute(get);
YourClass response = mapper.readValue(httpResponse.getEntity().getContent(), YourClass.class);
- Spring WebClient. There are more guides, just google them if you need. Simple get request example:
WebClient webClient = WebClient.builder().build();
YourClass conversionResponse = webClient.get()
.uri("https://your.host/endpoint")
.retrieve()
.bodyToMono(YourClass.class)
.block(Duration.ofSeconds(10));
Naturally there are more tools. Play around with them, and pick what's best for your specific need.

Chaosfire
- 4,818
- 4
- 8
- 23