场景:再接收到新生成的后缀名为.siddhi的文件后,需要使用HttpClient提交文件到搭载到siddhi的服务器上。
第一步,查看siddhi官方提供的api
siddhi创建应用的接口文档地址:Siddhi App APIs - Siddhi
上面样例是用curl的方式:
curl -X POST "https://localhost:9443/siddhi-apps" -H "accept: application/json" -H "Content-Type: text/plain" --data-binary @TestSiddhiApp.siddhi -u admin:admin -k
可以看到请求的是https的,为了避免证书相关问题麻烦,因此去siddhi-tooling和siddhi-runner下的deployment.yaml下修改配置文件,把id为“msf4j-https”下的schema配置项由https改为http
第二步,编写代码:
需要的maven依赖如下:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
代码如下:
public static void createSiddhiApp(String path,String url){
CloseableHttpClient httpClient=HttpClients.createDefault();
CloseableHttpResponse response=null;
try{
HttpPost httpPost=new HttpPost(url);
MultipartEntityBuilder builder=MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
httpPost.addHeader("Accept","application/json");
httpPost.addHeader("Content-Type","text/plain");
httpPost.addHeader("Authorization","Basic YWRtaW46YWRtaW4=");
File file=new File(path);
HttpEntity entity=new FileEntity(file);
httpPost.setEntity(entity);
response=httpClient.execute(httpPost);
HttpEntity responseEntity=response.getEntity();
Map resMap=JSONObject.parseObject(responseEntity.getContent(),Map.class);
System.out.println(resMap);
}catch(Exception e){
System.out.println("failure");
}finally{
try{
httpClient.close();
}catch(IOException e){
System.out.println("关闭失败");
}
}
}
若最终返回的结果是:
{ "type":"success", "message":"Siddhi App saved succesfully and will be deployed in next deployment cycle" }
说明上传成功了,如果得到的结果是:
{ "type": "conflict", "message": "There is a Siddhi App already exists with same name" }
说明现在已经存在了一个Appname相同的应用了。其他错误的情况可以查询在线接口文档