通过接口得到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();
}
}
posted @ 2022-05-20 10:20  天竹冰程  阅读(292)  评论(0编辑  收藏  举报