From 09001f561012e6c64d5361533fa1672ba03cb847 Mon Sep 17 00:00:00 2001 From: "1378012178@qq.com" <1378012178@qq.com> Date: Tue, 10 Jun 2025 11:11:45 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=BB=A3=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/nu/modules/proxy/ProxyApi.java | 54 ++++++++++++++----- 1 file changed, 41 insertions(+), 13 deletions(-) diff --git a/nursing-unit-api/src/main/java/com/nu/modules/proxy/ProxyApi.java b/nursing-unit-api/src/main/java/com/nu/modules/proxy/ProxyApi.java index 69e0e85..5b23466 100644 --- a/nursing-unit-api/src/main/java/com/nu/modules/proxy/ProxyApi.java +++ b/nursing-unit-api/src/main/java/com/nu/modules/proxy/ProxyApi.java @@ -1,31 +1,59 @@ package com.nu.modules.proxy; -import org.springframework.http.*; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; -import org.springframework.beans.factory.annotation.Autowired; @RestController @RequestMapping("/api/proxy") public class ProxyApi { - @Autowired - private RestTemplate restTemplate; + private final RestTemplate restTemplate = new RestTemplate(); // 不使用配置类,直接实例化 + /** + * 代理 GET 请求 + * @param apiUrl 三方接口的完整 URL + * @param params 请求的查询参数 + * @return 代理后的响应 + */ @GetMapping("/get") - public ResponseEntity proxyGet(@RequestParam String url, - @RequestHeader(required = false) HttpHeaders headers) { + public ResponseEntity proxyGet( + @RequestParam String apiUrl, + @RequestParam(required = false) String params) { + + String fullUrl = apiUrl + (params != null ? "?" + params : ""); + + HttpHeaders headers = new HttpHeaders(); + HttpEntity entity = new HttpEntity<>(headers); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); - return ResponseEntity.ok(response.getBody()); + + // 发起 GET 请求 + ResponseEntity response = restTemplate.exchange(fullUrl, HttpMethod.GET, entity, String.class); + + return response; // 返回代理后的响应 } + /** + * 代理 POST 请求 + * @param apiUrl 三方接口的完整 URL + * @param body 请求体 + * @return 代理后的响应 + */ @PostMapping("/post") - public ResponseEntity proxyPost(@RequestParam String url, - @RequestBody(required = false) String body, - @RequestHeader(required = false) HttpHeaders headers) { + public ResponseEntity proxyPost( + @RequestParam String apiUrl, + @RequestBody String body) { + + HttpHeaders headers = new HttpHeaders(); + HttpEntity entity = new HttpEntity<>(body, headers); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); - return ResponseEntity.ok(response.getBody()); + + // 发起 POST 请求 + ResponseEntity response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, String.class); + + return response; // 返回代理后的响应 } }