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

SpringBoot中RestTemplate exchange方法如何处理URL中的?编码问题?

Fixing RestTemplate Empty Response When URL Contains a Path with ?

Ah, I’ve dealt with this exact gotcha before! The root issue here is that the ? in your URL is part of the path segment, not a query parameter separator—but RestTemplate treats unencoded ? as the start of query params by default. That means your actual request is being sent to http://example.com/filter1/filter2/Art: Is It Value (dropping everything after the ?), which is why you’re getting an empty list instead of the expected data. Postman automatically handles encoding path-specific special characters, which is why it works there.

Here are two reliable ways to fix this:

This is the cleanest and most standards-compliant approach. UriComponentsBuilder will automatically encode all special characters in your path segments, including ?, spaces, and colons.

// Build the URI properly with encoding
URI uri = UriComponentsBuilder.fromHttpUrl("http://example.com")
        .path("/filter1/filter2/Art: Is It Value?")
        .build(true) // Pass true to enable encoding of path components
        .toUri();

// Now use the URI in your exchange call
ExampleResources<Test> exampleResources = restTemplate.exchange(
        uri, 
        HttpMethod.GET, 
        null, 
        new ParameterizedTypeReference<ExampleResources<Test>>() {}
).getBody();

The build(true) flag ensures that every part of the path is encoded according to RFC 3986, so your server receives the exact path you intended.

2. Manually Encode the Path Segment

If you prefer to stick with string concatenation, you can encode just the problematic path segment using URLEncoder. Just make sure to only encode the specific part with special characters, not the entire URL.

// Encode the problematic path segment
String encodedSegment = URLEncoder.encode("Art: Is It Value?", StandardCharsets.UTF_8);
String testUrl = "http://example.com/filter1/filter2/" + encodedSegment;

ExampleResources<Test> exampleResources = restTemplate.exchange(
        testUrl, 
        HttpMethod.GET, 
        null, 
        new ParameterizedTypeReference<ExampleResources<Test>>() {}
).getBody();

Note: URLEncoder replaces spaces with +, which most servers will accept, but UriComponentsBuilder uses %20 (the strict URI standard for path spaces). Either works, but the builder method is more robust.

The key takeaway here is that any special characters in path segments (not query params) need to be properly URL-encoded when using RestTemplate—unlike Postman, it doesn’t do this automatically for raw string URLs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 17:22:36