ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

通过接口得到json数据

2022-05-20 10:33:04  阅读:30  来源: 互联网

标签:String restApi 接口 data json new 数据 httpHeaders Optional


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();
}
}

标签:String,restApi,接口,data,json,new,数据,httpHeaders,Optional
来源: https://www.cnblogs.com/chengxiaoxiao/p/16291388.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有