如何在運行時呼叫 API 端點?我是這個行業的新手 我在我的 spring 專案中有一個端點,可以將產品(專案中的一個 json 檔案)保存到 MongoDB 我需要在用戶使用我的應用程式之前保存產品
uj5u.com熱心網友回復:
您需要客戶在適當的時間提出請求。有很多選擇,所以我只列出幾個:
- Java 提供的功能。不是很推薦,除非你想學習基礎知識。你可以在這里閱讀。
- Apache Http 組件。一個簡單的獲取請求示例:
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);
- 春天的網路客戶端。還有更多指南,如果需要,只需谷歌即可。簡單的獲取請求示例:
WebClient webClient = WebClient.builder().build();
YourClass conversionResponse = webClient.get()
.uri("https://your.host/endpoint")
.retrieve()
.bodyToMono(YourClass.class)
.block(Duration.ofSeconds(10));
自然還有更多的工具。與他們一起玩,并選擇最適合您的特定需求的東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443676.html
上一篇:身份驗證過濾器上的403禁止錯誤
