java RestTemplate GET 请求,带有编码的 URL

标签 java spring-mvc spring-boot resttemplate

我遇到过类似的问题,但他们似乎没有提供直接的示例。我正在尝试使用 RestTemplate 来 GET 和编码的 url。我有一个亚马逊类助手来生成签名的 url,但返回编码的 url,因此当我在 RestTemplate 中使用它时,它会再次编码。我应该输入 RestTemplate 的 url 应该如下所示;

http://webservices.amazon.com/onca/xml?AWSAccessKeyId=REMOVED&AssociateTag=REMOVED&Keywords=php&Operation=ItemSearch&ResponseGroup=Images,ItemAttributes,Offers&SearchIndex=All&Service=AWSECommerceService&Timestamp=2017-09-05T06:47:25.703Z&Signature=dthAE5BwmK2aZmSoIPRBwsPgCNwIv6JnXoqjC0QyRCQ=

但是我的亚马逊助手给了我这个;

http://webservices.amazon.com/onca/xml?AWSAccessKeyId=REMOVED&AssociateTag=REMOVED&Keywords=php&Operation=ItemSearch&ResponseGroup=Images%2CItemAttributes%2COffers&SearchIndex=All&Service=AWSECommerceService&Timestamp=2017-09-05T06%3A47%3A25.703Z&Signature=dthAE5BwmK2aZmSoIPRBwsPgCNwIv6JnXoqjC0QyRCQ%3D

这再次被编码打破了我的时间戳。我发现我可以很容易地使用字符串替换,但我正在寻找更好的方法。

我的代码如下所示;

SignedRequestsHelper 助手;

    try {
        helper = SignedRequestsHelper.getInstance(this.ENDPOINT, this.ACCESS_KEY_ID, this.SECRET_KEY);
    } catch (Exception e) {
        return "ERROR";
        //e.printStackTrace();
    }

    String requestUrl = null;

    Map<String, String> params = new HashMap<String, String>();
    ...
    requestUrl = helper.sign(params);
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setErrorHandler(new ResponseErrorHandler());
    ...
    try {
        String response = restTemplate.getForObject(requestUrl, String.class);
    } catch (HttpStatusCodeException exception) {
        return exception.getStatusCode().toString();
    }

最佳答案

养成阅读Javadoc的习惯:

For each HTTP method there are three variants: two accept a URI template string and URI variables (array or map) while a third accepts a URI. Note that for URI templates it is assumed encoding is necessary, e.g. restTemplate.getForObject("http://example.com/hotel list") becomes "http://example.com/hotel%20list". This also means if the URI template or URI variables are already encoded, double encoding will occur, e.g. http://example.com/hotel%20list becomes http://example.com/hotel%2520list). To avoid that use a URI method variant to provide (or re-use) a previously encoded URI. To prepare such an URI with full control over encoding, consider using UriComponentsBuilder.

关于java RestTemplate GET 请求,带有编码的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46048724/

相关文章:

java - java中是否有类似于 "Windows-MY"的unix key 存储?

java - Maven项目构建异常

java - HTTP 状态 400 - 客户端发送的请求在语法上不正确。 - 在使用 Hibernate 的 Spring MVC Web 应用程序中

spring - java.lang.IllegalArgumentException : IN (1): [IsIn, In]不支持redis查询派生 - Redis

java - keystore 和 cacerts 之间相同的别名不同的 key 正常吗?或者,如何在 keystore /cacerts之间导出/导入 key ?

java - 计算量是模型、 View 或 Controller 的一部分吗?

java - 装订莫里斯圆环图

java - ${} 变量未显示 - Spring MVC

java - Spring Boot 配置处理器,前缀的重复@ConfigurationProperties 定义

java - 如何使用第 3 方 @ConfigurationProperties @Bean?