通过接口得到json数据

private Optional<String> getResponseJson(RestApi restApi){
try {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLiCATION_JSON);
if(Optional.ofNullable(restApi.getAuthorizaton()).isPresent()){
httpHeaders.add("Authorization",restApi.getAuthrization());
}
httpentity<String> requestEntity = new httpentity<>(null,httpHeaders);
ResponeseEntity<String> responseEntity = restTemplate.exchange(restApi.getUrl(),restApi.getHttpMethod(),requestEntity,String.class);
return Optional.of(responseEntity.getBody());

}catch (Exception e){
log.error();
return Optional.empty();
}
}
private Optional<String> getResponseJson(RestApi restApi,DataMapping dataMapping,Map<String,Object> params){
try {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLiCATION_JSON);
if(Optional.ofNullable(restApi.getAuthorizaton()).isPresent()){
httpHeaders.add("Authorization",restApi.getAuthrization());
}
Map<String,Object> data = new HashMap<>();
if(dataMapping.getSourceDimCode() instanceof Map){
data.put((Map)dataMapping.getSourceDimCode());
}else{
data.putAll("sourceDimCode",dataMapping.getSourceDimCode());
}
if(Optional.ofNullable(params).isPresent()){
data.putAll(params);
}
String body = render(Optional.ofNullable(restApi.getBody()).orElse(""),data);
String url = render(restApi.getUrl(),data);
httpentity<String> requestEntity = new httpentity<>(body,httpHeaders);
ResponeseEntity<String> responseEntity = restTemplate.exchange(restApi.getUrl(),restApi.getHttpMethod(),requestEntity,String.class);
return Optional.of(responseEntity.getBody());

}catch (Exception e){
log.error();
return Optional.empty();
}
}

private String render(String template,Map<String,Object> data){
try {
StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
Configuration cfg = Configuration.defaultConfiguration();
GroupTemplate gt = new GroupTemplate(resourceLoader,cfg);
org.beetl.core.Template t = gt.getTemplate(template);
t.binding(data);
String str = t.render();
return str;

}catch (IoException e){
throw new AppException();
}
}

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...