使用java语言实现一个springboot代理转发功能
- User
使用java语言实现一个springboot代理转发功能
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
使用java语言实现一个springboot代理转发功能
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
以下是一个基于Spring Boot的HTTP代理转发实现,支持常见HTTP方法及请求/响应头传递:
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
@RestController
public class ProxyController {
// 可通过application.properties配置目标地址
private final String TARGET_BASE_URL = "http://target-service";
@RequestMapping("/proxy/**")
public void proxyRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
String path = request.getRequestURI().replaceFirst("/proxy", "");
String queryString = request.getQueryString();
String targetUrl = TARGET_BASE_URL + path;
if (queryString != null && !queryString.isEmpty()) {
targetUrl += "?" + queryString;
}
HttpURLConnection connection = (HttpURLConnection) new URL(targetUrl).openConnection();
connection.setRequestMethod(request.getMethod().toUpperCase());
// 复制请求头
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
connection.setRequestProperty(headerName, request.getHeader(headerName));
}
// 处理请求体
if (isBodyAllowed(request.getMethod())) {
connection.setDoOutput(true);
try (OutputStream os = connection.getOutputStream();
InputStream is = request.getInputStream()) {
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
}
}
// 获取响应状态码
int statusCode = connection.getResponseCode();
response.setStatus(statusCode);
// 复制响应头
connection.getHeaderFields().forEach((key, values) -> {
if (key != null && values != null) {
values.forEach(value -> response.addHeader(key, value));
}
});
// 处理响应体(包含错误流处理)
try (InputStream is = statusCode >= 400 ? connection.getErrorStream() : connection.getInputStream();
OutputStream os = response.getOutputStream()) {
if (is != null) {
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
}
}
}
private boolean isBodyAllowed(String method) {
return method.equalsIgnoreCase("POST") ||
method.equalsIgnoreCase("PUT") ||
method.equalsIgnoreCase("PATCH") ||
method.equalsIgnoreCase("DELETE");
}
}
路径处理:
/proxy/**的请求会被转发请求头传递:
请求体处理:
响应处理:
# application.properties
proxy.target.url=http://your-target-service
@Value("${proxy.target.url}")
private String targetBaseUrl;
connection.setConnectTimeout(5000);
connection.setReadTimeout(10000);
// 限制允许转发的域名
if (!isAllowedDomain(targetUrl)) {
response.sendError(403, "Domain not allowed");
return;
}
response.setHeader("Cache-Control", "no-cache");
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
GET http://localhost:8080/proxy/http://httpbin.org/get?test=1
POST http://localhost:8080/proxy/http://httpbin.org/post
这个实现提供了基本的代理转发功能,实际生产环境中建议: