首页 > 解决方案 > 查询参数中的 AsyncRestTemplate '#' 符号编码

问题描述

我正在使用AsyncRestTemplateSpringboot 1.5.2 服务对 Google Maps 进行 API 调用。不幸的是,我的一些搜索字符串包含井号/井号符号# ,并且在我的搜索参数中没有正确编码。我正在使用该exchange方法。

下面的地址示例05406, VT, BURLINGTON, 309 College St #10

@Service
public class ExampleAsyncRestTemplate {

    private AsyncRestTemplate asyncRestTemplate;

    @Autowired
    public ExampleAsyncRestTemplate() {
        this.asyncRestTemplate = new AsyncRestTemplate();
    }


    public ListenableFuture<ResponseEntity<T>> getGeoCodedAddress() {
         String googleUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=05406, VT, BURLINGTON, 309 College St #10&key=some_key";

         Map<String, String> uriVariables = new HashMap<>();
         uriVariables.put("address", "05406, VT, BURLINGTON, 309 College St #10");
         uriVariables.put("key", "some_key");

         return asyncRestTemplate.exchange(googleUrl, HttpMethod.GET, new HttpEntity<>(), GoogleResponse.class, uriVariables);
    }
}

生成的 URL 被编码为:

https://maps.googleapis.com/maps/api/geocode/json?address=05406,%20VT,%20BURLINGTON,%20309%20College%20St%20#10&key=some_key

请注意#,当它应该%23按照docs.

深入调试器,似乎#( 10&key=some_key) 之后的字符串被视为fragmentURL 的。因此为什么#永远不会被编码。

是否有人能够#使用 AsyncRestTemplate 在您的查询参数中提交标志?

我唯一能想到的就是用 替换#number它确实有效,但感觉很糟糕/次优。

谢谢你的帮助。

标签: javagoogle-mapsspring-bootencodingasyncresttemplate

解决方案


请注意,这googleUrl是一个将编码参数插入其中的模板。因此,您不能将实际参数作为 url 的一部分提供。您需要将字符串更改为这样的模板

final String googleUrl = "https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={key}";

这将返回正确的编码:

https://maps.googleapis.com/maps/api/geocode/json?address=05406,%20VT,%20BURLINGTON,%20309%20College%20St%20%2310&key=some_key

推荐阅读