Created
May 18, 2021 22:54
-
-
Save aossey/5fffe2a436862fe3e16034cbbf38f22f to your computer and use it in GitHub Desktop.
AWS SDK (Java 2) Example of Adding Custom User-Agent Value on S3 PutObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.MessageFormat; | |
import java.time.ZonedDateTime; | |
import java.time.format.DateTimeFormatter; | |
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; | |
import software.amazon.awssdk.core.sync.RequestBody; | |
import software.amazon.awssdk.regions.Region; | |
import software.amazon.awssdk.services.s3.S3Client; | |
import software.amazon.awssdk.services.s3.model.PutObjectRequest; | |
import software.amazon.awssdk.services.s3.model.S3Exception; | |
public class JavaSample { | |
// adjust these values to match your enviroment | |
private static String UA_STRING = "aossey-ua-test-value"; | |
private static String BUCKET_NAME = "aossey-ua-testing"; | |
private static String OBJECT_NAME = "ua-test-object.txt"; | |
private static Region REGION = Region.US_WEST_2; | |
public static void main(String[] args) { | |
// setup S3 Client using builder | |
S3Client s3 = S3Client.builder().region(REGION) | |
// set formated UA string using overrideConfiguration method | |
.overrideConfiguration(b -> b.putAdvancedOption(SdkAdvancedClientOption.USER_AGENT_PREFIX, UA_STRING)) | |
.build(); | |
try { | |
PutObjectRequest putObj = PutObjectRequest.builder().bucket(BUCKET_NAME).key(OBJECT_NAME).build(); | |
// get ISO formated Date Time string for object content and console output | |
String dtStamp = ZonedDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME); | |
s3.putObject(putObj, RequestBody.fromBytes( | |
// Add text content to file with ISO formated Date Time | |
MessageFormat.format("User-Agent Header Upload Test File on {0}", dtStamp).getBytes())); | |
System.out.println(MessageFormat.format("Put Complete at {0}", dtStamp)); | |
} catch (S3Exception e) { | |
System.err.println(e.getMessage()); | |
System.exit(1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment