如何使用Java Apache HttpClient将文件上传到公共AWS S3存储桶

时间:2019-05-05 22:27:59

标签: java amazon-s3 apache-httpclient-4.x apache-fluent-api

鉴于:名为“ YOUR_BACKET_NAME”的AWS S3存储桶具有公共访问权限,读/写

需要将文件上传到公共S3存储桶。

仅使用基本的最流行的Java库(例如Apache HTTP Client lib)。

不应使用AWS开发工具包。

1 个答案:

答案 0 :(得分:2)

    @Test
public void upload_file_to_public_s3_with_httpClient() throws Exception {

    String fileName = "test.txt";
    String bucketName = "YOUR_BACKET_NAME";
    String s3url = "https://" + bucketName + ".s3.amazonaws.com/" + fileName;
    String body = "BODY OF THE FILE";

    HttpEntity entity = MultipartEntityBuilder
            .create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("file", body.getBytes())
            .build();

    HttpResponse returnResponse = Request.Put(s3url).body(entity).execute().returnResponse();
    StatusLine statusLine = returnResponse.getStatusLine();
    String responseStr = EntityUtils.toString(returnResponse.getEntity());
    log.debug("response from S3 : line: {}\n body {}\n ", statusLine, responseStr);
}