restTemplate调用转义问题
例:
cmpUsername: username
cmpPassword: &dK83#5Cs0s(&等字符设计转义问题,如果用String直接拼接密码,则转义会出现问题)
String url;
url = cmpTokenUrl + "?username=" + cmpUsername + "&password=" + cmpPassword;
ResponseEntity<String> result;
HttpHeaders httpHeaders = getHttpHeaders();
log.info("getCmpTokenUrl,请求路径:{},请求头:{}", url, httpHeaders);
try {
result = restTemplate
.exchange(url, HttpMethod.POST,
new HttpEntity<>(null, httpHeaders), String.class);
} catch (Exception e) {
log.error("获取token出错:" + e);
throw new BizException(String.format("获取token失败:[%s]", e.getMessage()));
}
使用URIBuilder中的方法设置param:
URI uri;
try {
uri = new URI(cmpTokenUrl);
URIBuilder uriBuilder = new URIBuilder(uri);
List<NameValuePair> paramPairs = new ArrayList<>();
paramPairs.add(new BasicNameValuePair("username", cmpUsername));
paramPairs.add(new BasicNameValuePair("password", cmpPassword));
uriBuilder.setParameters(paramPairs);
uri = uriBuilder.build();
} catch (URISyntaxException e) {
log.error("构建URL发生异常: {}", e.getMessage());
throw new CheckException(String.format("构建URL发生异常:[%s]", e.getMessage()));
}
ResponseEntity<String> result;
HttpHeaders httpHeaders = getHttpHeaders();
log.info("getCmpTokenUrl,请求路径:{},请求头:{}", uri, httpHeaders);
try {
result = restTemplate
.exchange(uri, HttpMethod.POST,
new HttpEntity<>(null, httpHeaders), String.class);
} catch (Exception e) {
log.error("获取token出错:" + e);
throw new BizException(String.format("获取token失败:[%s]", e.getMessage()));
}