本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
亚马逊使用适用于 Java 2.x 的 SDK 查明示例
以下代码示例向您展示了如何使用AWS SDK for Java 2.x与 Amazon Pinpoint 一起执行操作和实现常见场景。
操作是大型程序的代码摘录,必须在上下文中运行。虽然操作向您展示了如何调用单个服务函数,但您可以在其相关场景和跨服务示例中查看操作的上下文。
场景是展示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。
每个示例都包含一个链接GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。
主题
操作
以下代码示例显示了如何创建广告活动。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 创建一个广告系列。
public static void createPinCampaign(PinpointClient pinpoint, String appId, String segmentId) { CampaignResponse result = createCampaign(pinpoint, appId, segmentId); System.out.println("Campaign " + result.name() + " created."); System.out.println(result.description()); } public static CampaignResponse createCampaign(PinpointClient client, String appID, String segmentID) { try { Schedule schedule = Schedule.builder() .startTime("IMMEDIATE") .build(); Message defaultMessage = Message.builder() .action(Action.OPEN_APP) .body("My message body.") .title("My message title.") .build(); MessageConfiguration messageConfiguration = MessageConfiguration.builder() .defaultMessage(defaultMessage) .build(); WriteCampaignRequest request = WriteCampaignRequest.builder() .description("My description") .schedule(schedule) .name("MyCampaign") .segmentId(segmentID) .messageConfiguration(messageConfiguration) .build(); CreateCampaignResponse result = client.createCampaign(CreateCampaignRequest.builder() .applicationId(appID) .writeCampaignRequest(request).build() ); System.out.println("Campaign ID: " + result.campaignResponse().id()); return result.campaignResponse(); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; }
-
有关 API 的详细信息,请参阅 CreateCampaignAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何创建分段。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static SegmentResponse createSegment(PinpointClient client, String appId) { try { Map<String, AttributeDimension> segmentAttributes = new HashMap<>(); segmentAttributes.put("Team", AttributeDimension.builder() .attributeType(AttributeType.INCLUSIVE) .values("Lakers") .build()); RecencyDimension recencyDimension = RecencyDimension.builder() .duration("DAY_30") .recencyType("ACTIVE") .build(); SegmentBehaviors segmentBehaviors = SegmentBehaviors.builder() .recency(recencyDimension) .build(); SegmentDemographics segmentDemographics = SegmentDemographics .builder() .build(); SegmentLocation segmentLocation = SegmentLocation .builder() .build(); SegmentDimensions dimensions = SegmentDimensions .builder() .attributes(segmentAttributes) .behavior(segmentBehaviors) .demographic(segmentDemographics) .location(segmentLocation) .build(); WriteSegmentRequest writeSegmentRequest = WriteSegmentRequest.builder() .name("MySegment") .dimensions(dimensions) .build(); CreateSegmentRequest createSegmentRequest = CreateSegmentRequest.builder() .applicationId(appId) .writeSegmentRequest(writeSegmentRequest) .build(); CreateSegmentResponse createSegmentResult = client.createSegment(createSegmentRequest); System.out.println("Segment ID: " + createSegmentResult.segmentResponse().id()); System.out.println("Done"); return createSegmentResult.segmentResponse(); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; }
-
有关 API 的详细信息,请参阅 CreateSegmentAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何创建应用程序。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static String createApplication(PinpointClient pinpoint, String appName) { try { CreateApplicationRequest appRequest = CreateApplicationRequest.builder() .name(appName) .build(); CreateAppRequest request = CreateAppRequest.builder() .createApplicationRequest(appRequest) .build(); CreateAppResponse result = pinpoint.createApp(request); return result.applicationResponse().id(); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; }
-
有关 API 的详细信息,请参阅 CreateAppAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何删除应用程序。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 删除应用程序。
public static void deletePinApp(PinpointClient pinpoint, String appId ) { try { DeleteAppRequest appRequest = DeleteAppRequest.builder() .applicationId(appId) .build(); DeleteAppResponse result = pinpoint.deleteApp(appRequest); String appName = result.applicationResponse().name(); System.out.println("Application " + appName + " has been deleted."); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 DeleteAppAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何删除终端节点。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 删除终端节点。
public static void deletePinEncpoint(PinpointClient pinpoint, String appId, String endpointId ) { try { DeleteEndpointRequest appRequest = DeleteEndpointRequest.builder() .applicationId(appId) .endpointId(endpointId) .build(); DeleteEndpointResponse result = pinpoint.deleteEndpoint(appRequest); String id = result.endpointResponse().id(); System.out.println("The deleted endpoint id " + id); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("Done"); }
-
有关 API 的详细信息,请参阅 DeleteEndpointAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何导出终端节点。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 导出端点。
public static void exportAllEndpoints(PinpointClient pinpoint, S3Client s3Client, String applicationId, String s3BucketName, String path, String iamExportRoleArn) { try { List<String> objectKeys = exportEndpointsToS3(pinpoint, s3Client, s3BucketName, iamExportRoleArn, applicationId); List<String> endpointFileKeys = objectKeys.stream().filter(o -> o.endsWith(".gz")).collect(Collectors.toList()); downloadFromS3(s3Client, path, s3BucketName, endpointFileKeys); } catch ( PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static List<String> exportEndpointsToS3(PinpointClient pinpoint, S3Client s3Client, String s3BucketName, String iamExportRoleArn, String applicationId) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH_mm:ss.SSS_z"); String endpointsKeyPrefix = "exports/" + applicationId + "_" + dateFormat.format(new Date()); String s3UrlPrefix = "s3://" + s3BucketName + "/" + endpointsKeyPrefix + "/"; List<String> objectKeys = new ArrayList<>(); String key; try { // Defines the export job that Amazon Pinpoint runs. ExportJobRequest jobRequest = ExportJobRequest.builder() .roleArn(iamExportRoleArn) .s3UrlPrefix(s3UrlPrefix) .build(); CreateExportJobRequest exportJobRequest = CreateExportJobRequest.builder() .applicationId(applicationId) .exportJobRequest(jobRequest) .build(); System.out.format("Exporting endpoints from Amazon Pinpoint application %s to Amazon S3 " + "bucket %s . . .\n", applicationId, s3BucketName); CreateExportJobResponse exportResult = pinpoint.createExportJob(exportJobRequest); String jobId = exportResult.exportJobResponse().id(); System.out.println(jobId); printExportJobStatus(pinpoint, applicationId, jobId); ListObjectsV2Request v2Request = ListObjectsV2Request.builder() .bucket(s3BucketName) .prefix(endpointsKeyPrefix) .build(); // Create a list of object keys. ListObjectsV2Response v2Response = s3Client.listObjectsV2(v2Request); List<S3Object> objects = v2Response.contents(); for (S3Object object: objects) { key = object.key(); objectKeys.add(key); } return objectKeys; } catch ( PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; } private static void printExportJobStatus(PinpointClient pinpointClient, String applicationId, String jobId) { GetExportJobResponse getExportJobResult; String status; try { // Checks the job status until the job completes or fails. GetExportJobRequest exportJobRequest = GetExportJobRequest.builder() .jobId(jobId) .applicationId(applicationId) .build(); do { getExportJobResult = pinpointClient.getExportJob(exportJobRequest); status = getExportJobResult.exportJobResponse().jobStatus().toString().toUpperCase(); System.out.format("Export job %s . . .\n", status); TimeUnit.SECONDS.sleep(3); } while (!status.equals("COMPLETED") && !status.equals("FAILED")); if (status.equals("COMPLETED")) { System.out.println("Finished exporting endpoints."); } else { System.err.println("Failed to export endpoints."); System.exit(1); } } catch (PinpointException | InterruptedException e) { System.err.println(e.getMessage()); System.exit(1); } } // Download files from an Amazon S3 bucket and write them to the path location. public static void downloadFromS3(S3Client s3Client, String path, String s3BucketName, List<String> objectKeys) { String newPath; try { for (String key : objectKeys) { GetObjectRequest objectRequest = GetObjectRequest.builder() .bucket(s3BucketName) .key(key) .build(); ResponseBytes<GetObjectResponse> objectBytes = s3Client.getObjectAsBytes(objectRequest); byte[] data = objectBytes.asByteArray(); // Write the data to a local file. String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); newPath = path + fileSuffix+".gz"; File myFile = new File(newPath); OutputStream os = new FileOutputStream(myFile); os.write(data); } System.out.println("Download finished."); } catch (S3Exception | NullPointerException | IOException e) { System.err.println(e.getMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 CreateExportJobAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何获取终端节点。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void lookupPinpointEndpoint(PinpointClient pinpoint, String appId, String endpoint ) { try { GetEndpointRequest appRequest = GetEndpointRequest.builder() .applicationId(appId) .endpointId(endpoint) .build(); GetEndpointResponse result = pinpoint.getEndpoint(appRequest); EndpointResponse endResponse = result.endpointResponse(); // Uses the Google Gson library to pretty print the endpoint JSON. Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) .setPrettyPrinting() .create(); String endpointJson = gson.toJson(endResponse); System.out.println(endpointJson); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("Done"); }
-
有关 API 的详细信息,请参阅 GetEndpointAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何导入区段。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 导入区段。
public static ImportJobResponse createImportSegment(PinpointClient client, String appId, String bucket, String key, String roleArn) { try { ImportJobRequest importRequest = ImportJobRequest.builder() .defineSegment(true) .registerEndpoints(true) .roleArn(roleArn) .format(Format.JSON) .s3Url("s3://" + bucket + "/" + key) .build(); CreateImportJobRequest jobRequest = CreateImportJobRequest.builder() .importJobRequest(importRequest) .applicationId(appId) .build(); CreateImportJobResponse jobResponse = client.createImportJob(jobRequest); return jobResponse.importJobResponse(); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; }
-
有关 API 的详细信息,请参阅 CreateImportJobAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何列出端点。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static void listAllEndpoints(PinpointClient pinpoint, String applicationId, String userId) { try { GetUserEndpointsRequest endpointsRequest = GetUserEndpointsRequest.builder() .userId(userId) .applicationId(applicationId) .build(); GetUserEndpointsResponse response = pinpoint.getUserEndpoints(endpointsRequest); List<EndpointResponse> endpoints = response.endpointsResponse().item(); // Display the results. for (EndpointResponse endpoint: endpoints) { System.out.println("The channel type is: "+endpoint.channelType()); System.out.println("The address is "+endpoint.address()); } } catch ( PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 GetUserEndpointsAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何列出区段。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 列出区段。
public static void listSegs( PinpointClient pinpoint, String appId) { try { GetSegmentsRequest request = GetSegmentsRequest.builder() .applicationId(appId) .build(); GetSegmentsResponse response = pinpoint.getSegments(request); List<SegmentResponse> segments = response.segmentsResponse().item(); for(SegmentResponse segment: segments) { System.out.println("Segement " + segment.id() + " " + segment.name() + " " + segment.lastModifiedDate()); } } catch ( PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 GetSegmentsAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何使用 Amazon Pinpoint 发送电子邮件和短信。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 发送电子邮件。
public static void sendEmail(PinpointClient pinpoint, String subject, String appId, String senderAddress, String toAddress) { try { Map<String,AddressConfiguration> addressMap = new HashMap<>(); AddressConfiguration configuration = AddressConfiguration.builder() .channelType(ChannelType.EMAIL) .build(); addressMap.put(toAddress, configuration); SimpleEmailPart emailPart = SimpleEmailPart.builder() .data(htmlBody) .charset(charset) .build() ; SimpleEmailPart subjectPart = SimpleEmailPart.builder() .data(subject) .charset(charset) .build() ; SimpleEmail simpleEmail = SimpleEmail.builder() .htmlPart(emailPart) .subject(subjectPart) .build(); EmailMessage emailMessage = EmailMessage.builder() .body(htmlBody) .fromAddress(senderAddress) .simpleEmail(simpleEmail) .build(); DirectMessageConfiguration directMessageConfiguration = DirectMessageConfiguration.builder() .emailMessage(emailMessage) .build(); MessageRequest messageRequest = MessageRequest.builder() .addresses(addressMap) .messageConfiguration(directMessageConfiguration) .build(); SendMessagesRequest messagesRequest = SendMessagesRequest.builder() .applicationId(appId) .messageRequest(messageRequest) .build(); pinpoint.sendMessages(messagesRequest); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
发送 SMS 消息。
public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId, String originationNumber, String destinationNumber) { try { Map<String, AddressConfiguration> addressMap = new HashMap<String, AddressConfiguration>(); AddressConfiguration addConfig = AddressConfiguration.builder() .channelType(ChannelType.SMS) .build(); addressMap.put(destinationNumber, addConfig); SMSMessage smsMessage = SMSMessage.builder() .body(message) .messageType(messageType) .originationNumber(originationNumber) .senderId(senderId) .keyword(registeredKeyword) .build(); // Create a DirectMessageConfiguration object. DirectMessageConfiguration direct = DirectMessageConfiguration.builder() .smsMessage(smsMessage) .build(); MessageRequest msgReq = MessageRequest.builder() .addresses(addressMap) .messageConfiguration(direct) .build(); // create a SendMessagesRequest object SendMessagesRequest request = SendMessagesRequest.builder() .applicationId(appId) .messageRequest(msgReq) .build(); SendMessagesResponse response= pinpoint.sendMessages(request); MessageResponse msg1 = response.messageResponse(); Map map1 = msg1.result(); //Write out the result of sendMessage. map1.forEach((k, v) -> System.out.println((k + ":" + v))); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
发送批量短信。
public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId, String originationNumber, String destinationNumber, String destinationNumber1) { try { Map<String, AddressConfiguration> addressMap = new HashMap<String, AddressConfiguration>(); AddressConfiguration addConfig = AddressConfiguration.builder() .channelType(ChannelType.SMS) .build(); // Add an entry to the Map object for each number to whom you want to send a message. addressMap.put(destinationNumber, addConfig); addressMap.put(destinationNumber1, addConfig); SMSMessage smsMessage = SMSMessage.builder() .body(message) .messageType(messageType) .originationNumber(originationNumber) .senderId(senderId) .keyword(registeredKeyword) .build(); // Create a DirectMessageConfiguration object. DirectMessageConfiguration direct = DirectMessageConfiguration.builder() .smsMessage(smsMessage) .build(); MessageRequest msgReq = MessageRequest.builder() .addresses(addressMap) .messageConfiguration(direct) .build(); // Create a SendMessagesRequest object. SendMessagesRequest request = SendMessagesRequest.builder() .applicationId(appId) .messageRequest(msgReq) .build(); SendMessagesResponse response= pinpoint.sendMessages(request); MessageResponse msg1 = response.messageResponse(); Map map1 = msg1.result(); // Write out the result of sendMessage. map1.forEach((k, v) -> System.out.println((k + ":" + v))); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 SendMessagesAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何更新终端节点。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 public static EndpointResponse createEndpoint(PinpointClient client, String appId) { String endpointId = UUID.randomUUID().toString(); System.out.println("Endpoint ID: " + endpointId); try { EndpointRequest endpointRequest = createEndpointRequestData(); UpdateEndpointRequest updateEndpointRequest = UpdateEndpointRequest.builder() .applicationId(appId) .endpointId(endpointId) .endpointRequest(endpointRequest) .build(); UpdateEndpointResponse updateEndpointResponse = client.updateEndpoint(updateEndpointRequest); System.out.println("Update Endpoint Response: " + updateEndpointResponse.messageBody()); GetEndpointRequest getEndpointRequest = GetEndpointRequest.builder() .applicationId(appId) .endpointId(endpointId) .build(); GetEndpointResponse getEndpointResponse = client.getEndpoint(getEndpointRequest); System.out.println(getEndpointResponse.endpointResponse().address()); System.out.println(getEndpointResponse.endpointResponse().channelType()); System.out.println(getEndpointResponse.endpointResponse().applicationId()); System.out.println(getEndpointResponse.endpointResponse().endpointStatus()); System.out.println(getEndpointResponse.endpointResponse().requestId()); System.out.println(getEndpointResponse.endpointResponse().user()); return getEndpointResponse.endpointResponse(); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; } private static EndpointRequest createEndpointRequestData() { try { List<String> favoriteTeams = new ArrayList<>(); favoriteTeams.add("Lakers"); favoriteTeams.add("Warriors"); HashMap<String, List<String>> customAttributes = new HashMap<>(); customAttributes.put("team", favoriteTeams); EndpointDemographic demographic = EndpointDemographic.builder() .appVersion("1.0") .make("apple") .model("iPhone") .modelVersion("7") .platform("ios") .platformVersion("10.1.1") .timezone("America/Los_Angeles") .build(); EndpointLocation location = EndpointLocation.builder() .city("Los Angeles") .country("US") .latitude(34.0) .longitude(-118.2) .postalCode("90068") .region("CA") .build(); Map<String,Double> metrics = new HashMap<>(); metrics.put("health", 100.00); metrics.put("luck", 75.00); EndpointUser user = EndpointUser.builder() .userId(UUID.randomUUID().toString()) .build(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset String nowAsISO = df.format(new Date()); return EndpointRequest.builder() .address(UUID.randomUUID().toString()) .attributes(customAttributes) .channelType("APNS") .demographic(demographic) .effectiveDate(nowAsISO) .location(location) .metrics(metrics) .optOut("NONE") .requestId(UUID.randomUUID().toString()) .user(user) .build(); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; }
-
有关 API 的详细信息,请参阅 UpdateEndpointAWS SDK for Java 2.xAPI 参考文档。
-
以下代码示例显示了如何更新频道。
- SDK for Java 2.x
-
注意
还有更多GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 private static SMSChannelResponse getSMSChannel(PinpointClient client, String appId) { try { GetSmsChannelRequest request = GetSmsChannelRequest.builder() .applicationId(appId) .build(); SMSChannelResponse response = client.getSmsChannel(request).smsChannelResponse(); System.out.println("Channel state is " + response.enabled()); return response; } catch ( PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; } private static void toggleSmsChannel(PinpointClient client, String appId, SMSChannelResponse getResponse) { boolean enabled = !getResponse.enabled(); try { SMSChannelRequest request = SMSChannelRequest.builder() .enabled(enabled) .build(); UpdateSmsChannelRequest updateRequest = UpdateSmsChannelRequest.builder() .smsChannelRequest(request) .applicationId(appId) .build(); UpdateSmsChannelResponse result = client.updateSmsChannel(updateRequest); System.out.println("Channel state: " + result.smsChannelResponse().enabled()); } catch ( PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 的详细信息,请参阅 GetSmsChannelAWS SDK for Java 2.xAPI 参考文档。
-