Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aossey/5fffe2a436862fe3e16034cbbf38f22f to your computer and use it in GitHub Desktop.
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
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