如何编码“?”在Springboot中的URL RestTemplate交换方法?

问题描述

我正在springboot中构建应用程序。 我有这段代码

String testUrl = "http://example.com/filter1/filter2/Art: Is It Value?";
ExampleResources<Test> exampleResources =
                    restTemplate.exchange(testUrl,HttpMethod.GET,null,new 
                    ParameterizedTypeReference<ExampleResources<Test>>() {
                    }).getBody();

它返回空列表。但是,如果我在Postman中对URL进行GET请求,我将得到正确的结果。经过一段时间的测试,我发现问号(“?”)引起了问题。我该如何处理?

解决方法

我认为您可以使用URLEncoder.encode方法对有问题的部分进行编码。

请看下面的示例代码。

String url = "http://example.com/filter1/filter2/";
String value = "Art: Is It Value?";
String newValue = URLEncoder.encode(value,StandardCharsets.UTF_8.toString());
String newUrl = url + newValue;

因此,您的newUrl如下所示。

http://example.com/filter1/filter2/Art%3A+Is+It+Value%3F

看看这是否有助于解决您的问题。