【发布时间】: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
假设:名为 YOUR_BACKET_NAME 的 AWS S3 存储桶具有公共访问权限 READ/WRITE
需要将文件上传到公共 S3 存储桶。
仅使用基本的最流行的 Java 库,例如 Apache HTTP 客户端库。
不应使用 AWS 开发工具包。
【问题讨论】:
标签: java amazon-s3 apache-httpclient-4.x apache-fluent-api
@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);
}
【讨论】: