才疏学浅,可能大家看不懂见谅
建立一个Application.java文件
@Component("appContext") @ConfigurationProperties(prefix = "checheyun") public class AppContext { String zhengshi_sid; String zhengshi_pid; String zhengshi_scode; }
然后在application-dev.yml中配置相关文件为
checheyun: zhengshi_sid: xx zhengshi_pid: xx zhengshi_scode: xxxxxxxxxxxxx
以上相关信息由接口提供方提供
接口方需要每一次请求都必须获取token则一个接口的实际调研操作如下:
Service层
@Service public class ZhengShiApi {
@Autowired AppContext app; @Autowired ZhengShiApi zhengShiApi;
//获取token,这里写了一个获取token的方法 @Cacheable(value = "zhengshitoken") public String getToken() throws CommonException { String url = "http://api.superepc.com/au/getToken?SID=" + app.getZhengshi_sid() + "&PID=" + app.getZhengshi_pid() + "&SCODE=" + app.getZhengshi_scode(); //getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象 JSONObject retData = template.getForEntity(url, JSONObject.class).getBody(); String code = retData.getString("responseCode"); if (!"0".equals(code)) { String message = retData.getString("responseMsg"); logger.info(message); throw new CommonException(CommonConstant.RESULT_CODE_EXPECTATION_FAILED, message); } Map<String, String> responseData = (Map<String, String>) retData.get("responseData"); return responseData.get("token"); }
/** * 根据tid查询行驶间隔里程 * 调研通用开发接口 */ public RetEntity<Object> getMileagesByTid(String Tid) throws CommonException { //这里是获取token String token = zhengShiApi.getToken(); String url = "http://api.superepc.com/maintain/getKilometer?tid=" + Tid + "&grant_code=" + token; JSONObject retData = template.getForEntity(url, JSONObject.class).getBody(); Object result = retData.get("result"); RetEntity<Object> ret = new RetEntity<>(); ret.setCode("200"); ret.setMessage("正常"); ret.setObject(result); return ret; }
}
而Controller这时对应的接口为:
@RestController @RequestMapping("/ccyBase/zhengshi") //@Api(value="报告类") public class ZhengShiApiController extends BaseController { @GetMapping("/mileages/byTypeCode/{Tid}") public RetEntity<Object> getMileagesByTid(@PathVariable("Tid") String Tid) throws CommonException { return zhengShiApi.getMileagesByTid(Tid); }
}