完整代码
- 对接海康开放平台通常,先引入SDK,然后更具API文档去写需要的实现类接口,接口里面拼接各种参数,然后调用SDK返回太烦了,代码不够简洁,受到Feign启发,将对海康平台接口访问封装成注解的形式
@HikHttp
public interface HikPlatformApiService {
@HikHttpRequest(value = HikApiConstant.personList, method = HttpMethod.POST)
public HikVo createNetEaseAcc(Map params);
}
-传统的调用方式
`
/**
* 调用POST接口,返回图片
* 接口实际url:https://ip:port/artemis/api/visitor/v1/record/pictures
* @return
*/
public static String callPostImgs() throws Exception {
ArtemisConfig config = new ArtemisConfig();
config.setHost("127.0.0.1"); // 代理API网关nginx服务器ip端口
config.setAppKey("20469790"); // 秘钥appkey
config.setAppSecret("lofnD6DbnBllHmk5YOyx");// 秘钥appSecret
final String getSecurityApi = "/artemis" + "/api/visitor/v1/record/pictures"; // 接口路径
Map<String, String> path = new HashMap<String, String>(2) {
{
put("https://", getSecurityApi);
}
};
Map<String, String> head = new HashMap<String, String>(2) { //get请求的head参数
{
put("headpost", "sky-test");
}
};
Map<String, String> query = new HashMap<String, String>(2) { //get请求的head参数
{
put("domainId", "0");
}
};
JSONObject jsonBody = new JSONObject();
jsonBody.put("svrIndexCode", "9ff58bc2-65a5-464b-b28c-daea67ba9569");
jsonBody.put("picUri", "/pic?9dda12i40-e*5b84626c4105m5ep=t=i3p*i=d1s*i=d3b*i1d3b*855925cea-96008b--2718943z855s=5i76=");
String body = jsonBody.toJSONString();
//参数根据接口实际情况设置
HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(config, path, body, query, null,"application/json",head);
try {
HttpResponse resp = result;
if (302==resp.getStatusLine().getStatusCode()) {
/*
获取图片数据保存到本地
注:1.对于有时效的图片,必须尽快保存到本地
2.若无时效,则可以直接保存location,后续自行访问获取
*/
Header header= resp.getFirstHeader("location");
String newUrl = header.getValue();
HttpGet httpget = new HttpGet(newUrl);
HttpClient httpClient = wrapClient(httpget.getURI().getScheme()+"://"+httpget.getURI().getHost());
HttpResponse execute = httpClient.execute(httpget);
HttpEntity entity = execute.getEntity();
InputStream in = entity.getContent();
Tools.savePicToDisk(in, "d:/", "test311.jpg");
}else{
System.out.println("下载出错");
}
} catch (Exception e) {
e.printStackTrace();
}
return getSecurityApi;
}
public static void main(String[] args) throws Exception {
String result = callPostApiGetOrgList();
System.out.println(result);
String VechicleDataResult = callPostApiGetRegions();
System.out.println(VechicleDataResult);
}
}
`
- 使用注解后,简洁明了
- 使用
先在启动类上加上@EnableHikHttpRequest("com.coder.gctool.test")注解,和对应要扫描的包
然后在该包下写接口
接口上添加@HikHttp注解,方法上添加 @HikHttpRequest注解就完成了
-测试