Slack will be deprecating the files.upload method for their API. In its place will be a new 3 step process. I’ve been successful executing Step 1 and Step 2 with Postman making calls to the Slack API. I’ve been successful executing Step 1 while making calls to the Slack API with my Java code. I have not been successful with Step 2 making calls to the Slack API with my Java code. I was hopeful to get some help with my Step 2 Java code.
Step 1: Make a HTTP GET Request to the files.getUploadURLExternal endpoint, passing the name of the file you intend to upload to Slack in a filename URL Query Parameter, and the size, in bytes, of the file in a length URL Query Parameter. This method is specifically documented here: https://api.slack.com/methods/files.getUploadURLExternal. The response you receive from files.getUploadURLExternal will include an upload_url value and a file_id argument
I was successful executing step 1 Slack API calls with Postman. You can see the proper query string parameters (Filename without path and size of file in bytes), the bear token and the response to the GET request.
Postman Step 1 successful
I was also successful executing step 1 Slack API calls with Java code. In the code, you can see the proper query string parameters (Filename without path and size of file in bytes), the bear token and the response to the GET request. The response consists of the upload_url and the file_id
URL urlObj = new URL("https://slack.com/api/files.getUploadURLExternal?filename=namefile&length=40000"); //URL object is a reference/address to a resource on the network
HttpsURLConnection connection = (HttpsURLConnection) urlObj.openConnection(); //Using the URL object, establish the HttpsURLConnection so we can connect to the files.getUploadURLExternal API
connection.setRequestMethod("GET"); //Specify what kind of request method this connection will have. It could be GET. It could be POST. It could be DELETE. It could be PUT.
connection.setRequestProperty("Authorization", "Bearer " + botUserOAuthAccessToken); //The Slack token must be authorized in this way
//When you send a request, you have to validate that the request was sent successfully and that you are able to get a valid response
int responseCode = connection.getResponseCode(); //Define the response code as an integer
System.out.println("Response CODE: "+responseCode);// Print the response code
if (responseCode == HttpsURLConnection.HTTP_OK) //Test if you get a valid response code
{
StringBuilder sb = new StringBuilder(); //Get the response that the API returns to us
Scanner scanner = new Scanner(connection.getInputStream()); //Use the scanner to read this response data from the InputStream
while (scanner.hasNext()) // StringBuilder is more efficient inside the while loop
{
sb.append(scanner.nextLine()); //Append the response to the StringBuilder
}
System.out.println(sb); //Print the string from the StringBuilder
ObjectMapper objectMapper = new ObjectMapper(); //To manipuate the data, convert the string to a normal Java object
JsonNode jsonNode = objectMapper.readTree(sb.toString()); //Convert Stringbuilder sb to JSON
String urlupload = jsonNode.get("upload_url").asText(); //Grab the url_upload from the JSON
System.out.println("url_upload: " + urlupload); //Print the url_upload value from the JSON
System.out.println(jsonNode.get("upload_url"));
String fileid = jsonNode.get("file_id").asText(); //Grab the file_id from the JSON
System.out.println("file_id: " + fileid); //Print the file_id value from the JSON
Here is the upload_url and file_id output from the code:
Response CODE: 200
{“ok”:true,”upload_url”:”https://files.slack.com/upload/v1/CwABAAAAWAoAAW3fBbTru-T7CgACF9bckBlvNhgMAAMLAAEAAAAJVDM2RVE4SFI2CwACAAAACVVERzZLUTVCNAsAAwAAAAtGMDc3NjJVTlgzNQAKAAQAAAAAAACcQAALAAIAAAAU_fItGMe4y90kNKMrXZEBrDuFQaMA”,”file_id”:”F07762UNX35″}
url_upload: https://files.slack.com/upload/v1/CwABAAAAWAoAAW3fBbTru-T7CgACF9bckBlvNhgMAAMLAAEAAAAJVDM2RVE4SFI2CwACAAAACVVERzZLUTVCNAsAAwAAAAtGMDc3NjJVTlgzNQAKAAQAAAAAAACcQAALAAIAAAAU_fItGMe4y90kNKMrXZEBrDuFQaMA
“https://files.slack.com/upload/v1/CwABAAAAWAoAAW3fBbTru-T7CgACF9bckBlvNhgMAAMLAAEAAAAJVDM2RVE4SFI2CwACAAAACVVERzZLUTVCNAsAAwAAAAtGMDc3NjJVTlgzNQAKAAQAAAAAAACcQAALAAIAAAAU_fItGMe4y90kNKMrXZEBrDuFQaMA”
file_id: F07762UNX35
Step 2: The response you receive from files.getUploadURLExternal will include an upload_url value and a file_id argument. Your next step is to make a HTTP POST Request to that upload_url passing the file that you wish to upload in the POST body, either as Raw Bytes or Multipart form encoded. This step is actually quite similar to the old files.upload approach. Whereas in that old approach, you were sending the file in a POST Request to the files.upload endpoint, in this new approach you are sending the file in a POST Request to upload_url you received.
I was successful executing Step 2 Slack API calls with Postman. I specified the upload_url, a bearer token, and I uploaded the file. When I clicked send, I received a 200 response OK.
Step 2 success Postman 1
Step 2 success Postman 2
Unfortunately, my Step 2 Slack API calls with Java code was not successful. I’ve setup everything the way I did in Postman. If you look at the code, the variable PathToReport represents the full path to my file. For example C:eclipseworkspaceTestGlobalNewsMavenRedesign202GlobalNewsMavenRedesign2019ExtentReportsGlobalNewsMavenRedesign2019Scripts.CheckGlobalNewsRunning05June202463152PM23.html
The variable urlupload represents the upload_url from step 1. I’ve specified a beare token, channel name and a multipart/form-data header
HttpClient httpclient = HttpClientBuilder.create().disableContentCompression().build(); //Initiate the HttpClient to send the test execution results report to
HttpPost httppost = new HttpPost(urlupload); //Post the Slack url
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); //Build the builder entity to host the test execution results report
httppost.addHeader("Content-Type","multipart/form-data; boundary=--");
FileBody fileBody = new FileBody(new File(PathToReport)); //Add the path of the test execution results report to the file body
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //Set up the builder structure to send the test execution results report and make sure it is browser compatible
builder.addPart("file", fileBody); //Add the file containing the test execution results report to the builder structure
builder.addTextBody("channels", channelName); //Add the channelName to the builder TextBody
builder.addTextBody("token", botUserOAuthAccessToken); //Add the token to the builder TextBody
httppost.setEntity(builder.build()); //Set the Entity for builder, post the test execution results report with all the builder components including file, channels and token
HttpResponse response = null; //Set the HTTPResponse to null
response = httpclient.execute(httppost); //The response is equal to the result of httppost
HttpEntity result = response.getEntity(); //HTTPEntity Result equals the response of getEntity
System.out.println("R E S P O N S E :"+response);
System.out.println("R E S U L T :"+result);
Here is the error I get from this code: I get 400 Bad request. I’ve specified multipart/form-data as a Content-Type but the response mentions a Content-Type of text/plain. Is this a permission issue
R E S P O N S E :HttpResponseProxy{HTTP/1.1 400 Bad Request [Content-Type: text/plain, Content-Length: 21, Connection: keep-alive, x-backend: miata-prod-pdx-v2-546b549895-dq2jc, date: Fri, 07 Jun 2024 23:27:00 GMT, x-envoy-upstream-service-time: 2, x-edge-backend: miata, x-slack-edge-shared-secret-outcome: shared-secret, server: envoy, via: envoy-edge-pdx-xykemedc, 1.1 09331f0822fc98eebaf04130a83dbd44.cloudfront.net (CloudFront), X-Cache: Error from cloudfront, X-Amz-Cf-Pop: SEA73-P1, X-Amz-Cf-Id: 8Md2UWHCua6JA_5VWCguLvNloI25wVKo_kDXnLzxlE_ea-SZoak93w==, Cross-Origin-Resource-Policy: cross-origin] ResponseEntityProxy{[Content-Type: text/plain,Content-Length: 21,Chunked: false]}}
R E S U L T :ResponseEntityProxy{[Content-Type: text/plain,Content-Length: 21,Chunked: false]}
What do I have to fix in order to get the Step 2 success that I got with Postman. Am I missing a header. Is my file object wrong. I’m hoping that somebody with more Java experience can point out something that will help me. Thank you for any help you can give me.