You need to enable JavaScript to run this app. RestTemplate发起GET请求报404错误,但相同请求用CURL可正常调用
优惠活动
大模型
产品
解决方案
定价
更多

RestTemplate发起GET请求报404错误,但相同请求用CURL可正常调用

同GET请求CURL正常返回、RestTemplate调用报404的问题排查与解决

复现场景

  • 调用目标为暴雪战网API接口,通过CURL发起GET请求时可正常获取响应,执行命令为:
curl -X GET 'https://us.api.blizzard.com/profile/wow/character/kiljaeden/n%C3%B8m?access_token=123&namespace=profile-us&locale=en_US'
  • 同一接口通过Java代码借助RestTemplate发起参数完全一致的请求时,直接抛出404错误,相关代码片段:
String testurl = "https://us.api.blizzard.com/profile/wow/character/kiljaeden/n%C3%B8m?access_token=123&namespace=profile-us&locale=en_US";

RestTemplate restTemplate = new RestTemplate();

String out = restTemplate.getForObject(testurl, String.class);

抛出的完整异常堆栈为:

org.springframework.web.client.HttpClientErrorException$NotFound: 404 Not Found
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:85)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:102)
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)

差异原因定位

两种客户端返回结果不一致的核心原因来自RestTemplate默认的URI二次编码逻辑:

  • 传入的URL字符串已经包含了URL编码后的特殊字符(对应角色名里的ø字符的编码值%C3%B8),CURL接收字符串格式的URL后会原样发起请求,不会对已有的编码内容做额外处理,因此可以正常命中服务端资源。
  • RestTemplate默认使用TemplateAndValues编码模式,会在解析字符串URL的过程中,把字符串中的%符号识别为未转义的普通字符,将其二次编码为%25。最终实际发送到服务端的请求路径会从原本的n%C3%B8m变成n%25C3%25B8m,和服务端存储的有效角色路径不匹配,因此返回404。

对应解决方法

  • 全局调整RestTemplate的URI编码模式,关闭对已编码内容的二次转义:
RestTemplate restTemplate = new RestTemplate();
DefaultUriBuilderFactory uriFactory = new DefaultUriBuilderFactory();
// 设置编码模式为组件级编码,避免对已编码的%字符做二次转义
uriFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT);
restTemplate.setUriTemplateHandler(uriFactory);
  • 跳过RestTemplate的字符串解析流程,手动将已编码完成的字符串转为URI对象再发起请求:
// 直接将已编码的字符串URL转为URI,绕开RestTemplate的编码逻辑
URI requestUri = URI.create(testurl);
String out = restTemplate.getForObject(requestUri, String.class);
  • 若场景为动态拼接URL(而非传入固定的已编码URL),可以将路径中的特殊字符单独做编码后再拼接为完整请求地址,避免编码逻辑混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 07:36:03