【JAVA--springboot 代理】
加载配置文件
- 首先需要创建一个Spring Boot项目,并添加以下依赖
- 创建主应用程序类
- 创建代理控制器类
- 在application.properties或application.yml中配置
- 添加CORS配置类
- 说明事项
- 测试如下:
首先需要创建一个Spring Boot项目,并添加以下依赖
- Spring Boot Starter Web
- Spring Boot DevTools (可选,用于开发时自动重启)
- Lombok (可选,用于简化代码)
创建主应用程序类
packagecom.sky;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.context.annotation.Bean;importorg.springframework.web.client.RestTemplate;@SpringBootApplicationpublicclassProxyServerApplication{publicstaticvoidmain(String[] args){SpringApplication.run(ProxyServerApplication.class, args);}@BeanpublicRestTemplaterestTemplate(){returnnewRestTemplate();}}创建代理控制器类
packagecom.sky.controller;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.http.HttpEntity;importorg.springframework.http.HttpHeaders;importorg.springframework.http.HttpMethod;importorg.springframework.http.ResponseEntity;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.client.RestTemplate;importjavax.servlet.http.HttpServletRequest;importjava.util.Enumeration;@RestControllerpublicclassProxyController{@Value("${proxy.target.url:http://localhost:8080}")privateString targetBaseUrl;privatefinalRestTemplate restTemplate;publicProxyController(RestTemplate restTemplate){this.restTemplate = restTemplate;}@RequestMapping(value ="/**", method ={RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.DELETE })publicResponseEntity<?>proxyRequest(HttpServletRequest request){try{System.err.println("Received request: "+ request.getMethod()+" "+ request.getRequestURI());String path = request.getRequestURI();String queryString = request.getQueryString();String fullUrl = targetBaseUrl + path +(queryString !=null?"?"+ queryString :"");// 复制请求头HttpHeaders headers =newHttpHeaders();Enumeration<String> headerNames = request.getHeaderNames();while(headerNames.hasMoreElements()){String headerName = headerNames.nextElement(); headers.add(headerName, request.getHeader(headerName));}// 读取请求体String body =null;if("POST".equalsIgnoreCase(request.getMethod())||"PUT".equalsIgnoreCase(request.getMethod())||"PATCH".equalsIgnoreCase(request.getMethod())){ body =StreamUtils.copyToString(request.getInputStream(),StandardCharsets.UTF_8);}// 创建包含请求体的实体HttpEntity<String> entity =newHttpEntity<>(body, headers);// 获取请求方法HttpMethod method =HttpMethod.valueOf(request.getMethod());// 发送代理请求ResponseEntity<String> response = restTemplate.exchange( fullUrl, method, entity,String.class);returnResponseEntity.status(response.getStatusCode()).headers(response.getHeaders()).body(response.getBody());}catch(Exception e){System.err.println("代理错误: "+ e.getMessage());returnResponseEntity.status(500).body("{\"error\": \"代理请求失败\"}");}}}在application.properties或application.yml中配置
在resources目录下创建application.yml 文件,如下图:

application.properties 文件内容如下:
server.port=5005
proxy.target.url=http://localhost:8080
添加CORS配置类
packagecom.sky.config;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.cors.CorsConfiguration;importorg.springframework.web.cors.UrlBasedCorsConfigurationSource;importorg.springframework.web.filter.CorsFilter;@ConfigurationpublicclassCorsConfig{@BeanpublicCorsFiltercorsFilter(){CorsConfiguration config =newCorsConfiguration(); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*");UrlBasedCorsConfigurationSource source =newUrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config);returnnewCorsFilter(source);}}说明事项
Spring Boot支持从外部位置加载配置文件,而不是仅限于jar包内部。你可以将配置文件(如application.properties或application.yml)放在jar包同一目录下,或者放在特定的子目录中,Spring Boot会优先使用外部配置文件
通过命令行参数覆盖配置文件中的设置
java -jar sky-proxy-1.0-SNAPSHOT.jar --server.port=8081
–proxy.target.url=http://localhost:8080
测试如下:
启动脚本
java -jar sky-proxy-1.0-SNAPSHOT.jar --server.port=8081 --proxy.target.url=http://localhost:8080
注意事项:
windows 系统在cmd 或shellpower中执行时,出现乱码时,需要先执行一下:
chcp 65001 此指令表示cmd 使用utf-8 编码
使用Bruno工具发送请求,正确返回通过,如下图:
