【问题标题】:java RestTemplate GET request with encoded URL带有编码 URL 的 java RestTemplate GET 请求
【发布时间】:2017-09-05 06:57:02
【问题描述】:

我遇到过类似的问题,但他们似乎没有提供直接的例子。我正在尝试使用 RestTemplate 通过编码的 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();
    }

【问题讨论】:

    标签: java spring-mvc spring-boot resttemplate


    【解决方案1】:

    养成阅读Javadoc的习惯:

    对于每个 HTTP 方法,有三种变体:两种接受一个 URI 模板字符串和 URI 变量(数组或映射),而第三个接受 一个 URI。请注意,对于 URI 模板,假定编码是 必要的,例如restTemplate.getForObject("http://example.com/hotel list") 变为 "http://example.com/hotel%20list"。这也意味着如果 URI 模板或 URI 变量已经编码,双重编码 会发生,例如http://example.com/hotel%20list 变为 http://example.com/hotel%2520list)。为避免这种情况,请使用 URI 方法 提供(或重用)先前编码的 URI 的变体。准备 这样一个完全控制编码的 URI,考虑使用 UriComponentsBuilder。

    【讨论】:

    • 好的,我看到 getForObject 的 3 个变体。而且我已经看到了 UriComponentsBuilder。假设我有一个编码的 url 开头。如何解码?
    • @user5500750 您不会对其进行解码,而是将其转换为 URI 并使用接受 URI 的重载方法之一。上面的措辞能再清楚一点吗?
    • 除非我已经有一个由助手创建的编码 url。你可以在我的代码中看到这一点。我已经将我的参数输入到返回 url 的助手中。我不想创建一个 URI 模板字符串,然后将其输入到 getForObject 方法中。我是Java新手,所以希望我说得通。我明白你在说什么,但把它放到代码中是个问题。
    • @user5500750 如果您是 Java 新手,那么您不是为 Spring 项目编写代码的人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2019-10-25
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2013-04-21
    相关资源
    最近更新 更多