You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot自定义代理开发:请求头与RequestParam问题求助

代理服务问题解决方案

1. GET响应乱码与POST/PUT请求头I/O错误

响应乱码修复

  • 统一响应编码为UTF-8,配置RestTemplate的消息转换器强制指定字符集:
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().stream()
    .filter(converter -> converter instanceof StringHttpMessageConverter)
    .map(converter -> (StringHttpMessageConverter) converter)
    .forEach(converter -> converter.setDefaultCharset(StandardCharsets.UTF_8));
  • 若目标服务返回二进制数据,改用byte[]或Resource类型接收响应,避免字符串编码转换导致乱码。

请求头导致的I/O错误修复

  • 过滤系统级请求头,避免与框架自动生成的头冲突:
HttpHeaders targetHeaders = new HttpHeaders();
// 仅保留自定义业务头,跳过Content-Length、Host等系统头
requestHeaders.forEach((key, value) -> {
    if (!Arrays.asList("Content-Length", "Host", "Connection").contains(key)) {
        targetHeaders.add(key, value);
    }
});
  • 禁止手动设置Content-Length头,交由框架自动计算请求体长度,避免因长度不匹配触发"insufficient data written"错误。

2. GET请求参数截断问题

  • 使用UriComponentsBuilder构建完整URL,避免字符串拼接导致的参数丢失:
// 从前端接收的基础URL
String baseUrl = "https://login.money.net/money/example/api/ipg/v1/recon/api/remita/txn-proc-requests-report?page=0";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl);
// 追加其他参数(如果有的话)
builder.queryParam("size", 20)
       .queryParam("startDate", "2024-01-01");
// 生成完整URL
String fullRequestUrl = builder.build(true).toUriString();
  • 后端接收前端传入的URL时,使用@RequestParam而非@PathVariable,并确保解码完整:
@GetMapping("/proxy")
public ResponseEntity<?> proxyGet(@RequestParam("url") String url) throws UnsupportedEncodingException {
    String decodedUrl = URLDecoder.decode(url, StandardCharsets.UTF_8.name());
    // 后续转发逻辑
}
  • 日志打印完整的解码后URL,确认参数是否全部保留,排查前端传递时的编码问题。

内容的提问来源于stack exchange,提问作者Tobiloba Faseyitan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 08:43:24