【问题标题】:how to upload a file to a public AWS S3 bucket with Java Apache HttpClient如何使用 Java Apache HttpClient 将文件上传到公共 AWS S3 存储桶
【发布时间】:2021-03-10 10:09:25
【问题描述】:

假设:名为 YOUR_BACKET_NAME 的 AWS S3 存储桶具有公共访问权限 READ/WRITE

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

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

不应使用 AWS 开发工具包。

【问题讨论】:

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


    【解决方案1】:
        @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);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 2018-04-25
      • 2017-09-24
      • 2021-03-06
      • 2021-02-07
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 2021-05-05
      相关资源
      最近更新 更多