0

I'm trying to publish image from my automation suite to slack channel.
URL to hit: https://slack.com/api/files.upload
Body is form-data type and it has,

  • file - image file upload
  • initial_comment - some string
  • channels - the slack channel to be published.

i tried using MultipartEntity class inside HttpPost

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);

Im getting the success response from http post. but the image is not posted in slack channel.any help!

MSD
  • 1,409
  • 12
  • 25

1 Answers1

0

The problem was with header. Actually, this slack api gives 200 response even for the wrong header. Working code:

        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);
MSD
  • 1,409
  • 12
  • 25