我遇到过类似的问题,但他们似乎没有提供直接的示例。我正在尝试使用 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/