介绍:springcloud项目server子模块内部集成了低代码平台来配置通用列表查询,需要对低代码配置权限,低代码使用不了server模块的feign调用,只能用http请求去调用分布式项目的用户模块来获取权限,通过restTemplate调用接口,postman携带token信息可以直接调通用户中心,但是通过低代码调不到,报500网络错误,查看用户中心那边日志后发现是没拿到token,说明需要低代码内部通过htttp请求携带token去请求。
第一步:通过方法获取页面传入的token
//使用RequestContextHolder工具获取request相关变量
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
// 获取request
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("Authorization");
}
第二步:将token信息设置到请求头中
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Authorization", token);
HttpEntity requestEntity = new HttpEntity(requestHeaders);
第三步:通过restTemplate调用http请求:
HttpEntity requestEntity = new HttpEntity(requestHeaders);
ResponseEntity<Result> response = null;
try {
if (StringUtils.isNotBlank(scopeKeys)) {
response = restTemplate.exchange(getMnsUrl + "?key=" + key, HttpMethod.GET, requestEntity, Result.class);
}
} catch (RestClientException e) {
e.printStackTrace();
}
if (null != response) {
Result body = response.getBody();
}
报错:
总结:代码文章来源:https://www.toymoban.com/news/detail-764239.html
//使用RequestContextHolder工具获取request相关变量
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpHeaders requestHeaders = new HttpHeaders();
if (attributes != null) {
// 获取request
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("Authorization");
requestHeaders.set("Authorization", token);
}
HttpEntity requestEntity = new HttpEntity(requestHeaders);
ResponseEntity<Result> response = null;
try {
if (StringUtils.isNotBlank(scopeKeys)) {
response = restTemplate.exchange(getMnsUrl + "?key=" + key, HttpMethod.GET, requestEntity, Result.class);
}
} catch (RestClientException e) {
e.printStackTrace();
}
if (null != response) {
Result body = response.getBody();
}
ps:postman通过公网ip携带token直接调通用户中心是因为能直接拿到,postman携带token调低代码,低代码再调用户中心报错是因为间接调用,那边取不到token,这种情况需要把token通过请求头传过去。文章来源地址https://www.toymoban.com/news/detail-764239.html
到了这里,关于(下篇)java通过http请求请求三方接口:设置请求头,请求体的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!