如何在运行时调用API端点?

发布于 2025-01-13 20:57:06 字数 104 浏览 2 评论 0原文

如何在运行时调用 API 端点? 我是这个行业的新手 我的 spring 项目中有一个端点,用于将产品(项目中的 json 文件)保存到 MongoDB 我需要在用户使用我的应用程序之前保存产品

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情独悲 2025-01-20 20:57:06

您需要客户在适当的时间提出请求。有很多选项,因此我将仅列出其中几个:

  1. Java 提供的功能。不推荐,除非你想学习基础知识。您可以在此处阅读
  2. Apache HttpComponent。一个简单的获取请求示例:
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);
  1. Spring 网络客户端。还有更多指南,如果需要,只需 google 即可。简单的get请求示例:
WebClient webClient = WebClient.builder().build();
YourClass conversionResponse = webClient.get()
        .uri("https://your.host/endpoint")
        .retrieve()
        .bodyToMono(YourClass.class)
        .block(Duration.ofSeconds(10));

自然还有更多的工具。尝试一下它们,然后选择最适合您的特定需求的。

You need a client to make the request at the appropriate time. There are lots of options, so i will list only a few:

  1. Java provided functionality. Not really recommended, unless you want to learn the basics. You can read here.
  2. 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);
  1. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文