Amazon Simple Storage Service
开发人员指南 (API 版本 2006-03-01)
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 Amazon AWS 入门

使用AWS SDK for Java管理网站

以下示例说明如何使用AWS SDK for Java管理存储桶的网站配置。要将网站配置添加到存储桶,请提供存储桶名称和网站配置。网站配置必须包含索引文档,并且可包含可选的错误文档。这些文档必须已存在于存储桶中。有关更多信息,请参阅 PUT 存储桶网站。有关 Amazon S3 网站功能的更多信息,请参阅在 Amazon S3 上托管静态网站

以下示例使用AWS SDK for Java将网站配置添加到存储桶,检索并输出配置,然后删除配置并确认删除操作。有关如何创建和测试有效示例的说明,请参阅 测试 Amazon S3 Java 代码示例

import java.io.IOException; import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.BucketWebsiteConfiguration; public class WebsiteConfiguration { public static void main(String[] args) throws IOException { String clientRegion = "*** Client region ***"; String bucketName = "*** Bucket name ***"; String indexDocName = "*** Index document name ***"; String errorDocName = "*** Error document name ***"; try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withRegion(clientRegion) .withCredentials(new ProfileCredentialsProvider()) .build(); // Print the existing website configuration, if it exists. printWebsiteConfig(s3Client, bucketName); // Set the new website configuration. s3Client.setBucketWebsiteConfiguration(bucketName, new BucketWebsiteConfiguration(indexDocName, errorDocName)); // Verify that the configuration was set properly by printing it. printWebsiteConfig(s3Client, bucketName); // Delete the website configuration. s3Client.deleteBucketWebsiteConfiguration(bucketName); // Verify that the website configuration was deleted by printing it. printWebsiteConfig(s3Client, bucketName); } catch(AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch(SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } private static void printWebsiteConfig(AmazonS3 s3Client, String bucketName) { System.out.println("Website configuration: "); BucketWebsiteConfiguration bucketWebsiteConfig = s3Client.getBucketWebsiteConfiguration(bucketName); if (bucketWebsiteConfig == null) { System.out.println("No website config."); } else { System.out.println("Index doc: " + bucketWebsiteConfig.getIndexDocumentSuffix()); System.out.println("Error doc: " + bucketWebsiteConfig.getErrorDocument()); } } }