Spring Boot RestTemplate带参数GET请求404错误求助
解决RestTemplate带查询参数时返回404的问题
你遇到的核心问题是RestTemplate传递查询参数的方式不正确,导致实际发送到API的请求并没有带上预期的workspace_id查询参数,所以API中带params=["workspace_id"]的控制器方法匹配不到,最终返回404。
先拆解下代码里的问题:你调用restTemplate.exchange()时,最后传入的params参数是用来替换URI路径中的占位符(比如/test/{workspace_id})的,而非添加URL查询参数。但你的API是通过?workspace_id=xxx的形式接收参数,所以这种方式根本没把参数加到请求URL里,API自然找不到对应的控制器方法。
下面给你两种可行的修复方案:
方案一:用UriComponentsBuilder构建带查询参数的URI
这种方式最直观,能明确构建出包含查询参数的完整请求URL:
override fun get(authentication : OAuth2Authentication, workspaceId : UUID ) : String { val token = (authentication.details as OAuth2AuthenticationDetails).tokenValue val headers = HttpHeaders() headers.setBearerAuth(token) val entity = HttpEntity<Any>(headers) // 构建带查询参数的URI val uri = UriComponentsBuilder.fromUriString("http://localhost:13001/test") .queryParam("workspace_id", workspaceId) .build() .toUri() return restTemplate.exchange(uri, HttpMethod.GET, entity, String::class.java).body!! }
方案二:在endpoint字符串中添加查询参数占位符
如果你想继续使用params参数传递值,需要把endpoint改成包含查询参数占位符的形式:
override fun get(authentication : OAuth2Authentication, workspaceId : UUID ) : String { val token = (authentication.details as OAuth2AuthenticationDetails).tokenValue val headers = HttpHeaders() headers.setBearerAuth(token) val entity = HttpEntity<Any>(headers) val params = HashMap<String, UUID>() params["workspace_id"] = workspaceId // 注意endpoint要包含查询参数占位符 val endpoint = "http://localhost:13001/test?workspace_id={workspace_id}" return restTemplate.exchange(endpoint, HttpMethod.GET, entity, String::class.java, params).body!! }
额外验证点
确认你的API控制器配置无问题:
params = ["workspace_id"]表示仅当请求包含workspace_id查询参数时才匹配该方法,这部分逻辑是正确的- UUID参数的解析逻辑正常(你的无参数方法能运行,说明这部分不是问题)
修复后再用Postman测试,应该就能正常匹配到API的控制器方法,不会再返回404了。
内容的提问来源于stack exchange,提问作者Andrey Kaplan
相关产品推荐
相关产品推荐

