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

how to upload a file to a public AWS S3 bucket with Java Apache HttpClient

给定:名为 YOUR_BACKET_NAME 的 AWS S3 存储桶具有 public 访问权限 READ/WRITE

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

仅使用最基本的最流行的 Java 库,例如 Apache HTTP 客户端库。

不应使用 AWS SDK。

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