javarestemplate获取带有编码url的请求

lpwwtiir  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(336)

我也遇到过类似的问题,但它们似乎没有提供一个直接的例子。我正在尝试使用restemplate获取一个编码的url。我有一个amazon类助手来生成一个签名的url,但是返回编码的url,所以当我在restemplate中使用它时,它会再次编码。我应该输入restemplate的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();
    }
0g0grzrc

0g0grzrc1#

养成阅读javadoc的习惯:
对于每个http方法,有三个变体:两个接受uri模板字符串和uri变量(数组或Map),而第三个接受uri。请注意,对于uri模板,假定编码是必需的,例如resttemplate.getforobject(“http://example.com/hotel 列表“)变成”http://example.com/hotel%20list". 这也意味着如果uri模板或uri变量已经编码,则会发生双重编码,例如。http://example.com/hotel%20list 变成http://example.com/hotel%2520list). 为了避免这种情况,请使用uri方法变量来提供(或重用)以前编码的uri。要准备这样一个完全控制编码的uri,请考虑使用uricomponentsbuilder。

相关问题