Talk about uploading files using slack API with Apache HttpPost

The stackoverflow article I found while trying to upload a file with the Slack API was a bit indigestive, so I'll write it down. How to upload a file using Apache HttpPost Even if you write it as above, it will be 200 OK, but "no file data" Therefore, the file upload has not been successful. I had read this article in advance, so POST multipart / form-data with HttpURLConnection I wondered if I should use InputStream, and when I checked the argument of the method in the official document, it was still there. MultipartEntityBuilder

The token used for the API has been pre-injected.

public String post(File file) {
		CloseableHttpClient client = HttpClientBuilder.create()
		        .build();
		HttpEntity requestEntity=null;
		try {
			requestEntity = MultipartEntityBuilder.create()
					.addTextBody("token", token)
					.addTextBody("filetype", "jpg")
.addBinaryBody("file", new FileInputStream(file),ContentType.IMAGE_JPEG,"graph")
			        .build();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		HttpPost post = new HttpPost(URL);
		String result = null;
		try {
			post.setEntity(requestEntity);
			HttpResponse response = client.execute(post);
			logger.info("Status: {}", response.getStatusLine());
			result = collectResponse(response);
	
		} catch (IOException e) {
			logger.error("While posting", e);
		}
		return result;
	}
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.3.1</version>
</dependency>

Reference link: https://github.com/salahsheikh/jpushbullet/blob/master/src/main/java/com/github/silk8192/jpushbullet/PushbulletClient.java

Recommended Posts

Talk about uploading files using slack API with Apache HttpPost
About Apache Inference API
Chew about API
Talk about uploading files using slack API with Apache HttpPost
About Gradle's compile, api, implementation, etc.
About Apache Inference API
Download large files with Apache JMeter
[Java] Handle Excel files with Apache POI