Java用HttpClient提交文件到siddhi

场景:再接收到新生成的后缀名为.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相同的应用了。其他错误的情况可以查询在线接口文档 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值