LoginSignup
1
1

More than 5 years have passed since last update.

Apache HttpPostでslackAPIを使ってファイルアップロードする話

Last updated at Posted at 2018-05-04

Slack APIでファイルをアップロードしようとしていたときに見つけたstackoverflowの記事がちょっと消化不良だったので書いておく。
How to upload a file using Apache HttpPost

上記の通りに書いても200 OKにはなるものの、"no file data"
になるので、ファイルアップロードには成功していない。
事前にこの記事を読んでいたので、
HttpURLConnectionでmultipart/form-dataをPOSTする
InputStream使えばいいのかなーと公式ドキュメントのメソッドの引数確認したらやはりありました。
MultipartEntityBuilder

APIに使うtokenは事前にインジェクト済みです。

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>

参考リンク:https://github.com/salahsheikh/jpushbullet/blob/master/src/main/java/com/github/silk8192/jpushbullet/PushbulletClient.java

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1