【问题标题】:slack api : files to upload to slack channelslack api : 上传到 slack 频道的文件
【发布时间】:2020-09-11 05:15:47
【问题描述】:

我正在尝试将图像从我的自动化套件发布到松弛通道。
要点击的网址:https://slack.com/api/files.upload
Body 是表单数据类型,它有,

  • 文件-图片文件上传
  • initial_comment - 一些字符串
  • channels - 要发布的松弛通道。

我尝试在 HttpPost 中使用 MultipartEntity 类

MultipartEntity multiPartEntity = new MultipartEntity();

FileBody fileBody = new FileBody(file);
//Prepare payload
multiPartEntity.addPart("file", fileBody);
multiPartEntity.addPart("file_type", new StringBody("JPG"));
multiPartEntity.addPart("initial_comment", new StringBody("cat shakes"));
multiPartEntity.addPart("channels", new StringBody("bot-e2e-report"));

//Set to request body
postRequest.setEntity(multiPartEntity);

我从 http post 获得成功响应。但是图片没有发布在松弛频道中。任何帮助!

【问题讨论】:

    标签: java post http-post slack multipartentity


    【解决方案1】:

    问题出在标题上。实际上,即使是错误的标头,这个 slack api 也会给出 200 响应。工作代码:

            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                //Set various attributes
                MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
    
                entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                entitybuilder.addBinaryBody("file", file);
                entitybuilder.addTextBody("initial_comment", "cat");
                entitybuilder.addTextBody("channels","bot-e2e-report");
                HttpEntity mutiPartHttpEntity = entitybuilder.build();
                RequestBuilder reqbuilder = RequestBuilder.post("https://slack.com/api/files.upload");
                reqbuilder.setEntity(mutiPartHttpEntity);
    
                //set Header
                reqbuilder.addHeader("Authorization", "Bearer xoxb-16316687382-1220823299362-fdkBklPrY7rc72bQk3WSOSjD");
    
                HttpUriRequest multipartRequest = reqbuilder.build();
                // call post
                HttpResponse response = httpclient.execute(multipartRequest);
                // Parse the response
                HttpEntity entity = response.getEntity();
                String json = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(json);
    

    【讨论】:

      猜你喜欢
      • 2020-05-21
      • 2022-01-12
      • 2022-06-18
      • 2023-04-08
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多