如何使用AWS Java SDK连接SageMaker并调用Jupyter Notebook创建的端点?
Hey there! I’ve walked many developers through this exact workflow, so let me break it down into clear, actionable steps for you.
1. Set Up Dependencies & AWS Credentials
First, make sure you’ve got the AWS Java SDK for SageMaker added to your project. If you’re using Maven, drop this into your pom.xml:
<dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-sagemaker</artifactId> <version>1.12.500</version> <!-- Use the latest stable version available --> </dependency>
For Gradle users, add this to your build.gradle:
implementation 'com.amazonaws:aws-java-sdk-sagemaker:1.12.500'
Next, configure your AWS credentials. The safest way is to use the default credentials provider chain—it automatically checks:
- Environment variables (
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY) - The
~/.aws/credentialsfile on your local machine - IAM roles if your code runs on AWS services like EC2 or EKS
Avoid hardcoding credentials in your code for production environments.
2. Initialize the SageMaker Client
Create a SageMaker client instance tied to the AWS region where your endpoint is hosted:
import com.amazonaws.services.sagemaker.AmazonSageMaker; import com.amazonaws.services.sagemaker.AmazonSageMakerClientBuilder; public class SageMakerConnector { public static void main(String[] args) { // Replace "us-east-1" with your endpoint's region AmazonSageMaker sageMakerClient = AmazonSageMakerClientBuilder.standard() .withRegion("us-east-1") .build(); } }
3. Call Your Existing SageMaker Endpoint
This is the core part—using the invokeEndpoint method to send requests to the endpoint you created in Jupyter Notebook. You’ll need three key pieces of info:
- Your endpoint’s exact name (from your notebook setup)
- The content type your model expects (e.g.,
application/json,text/csv) - A payload formatted to match what your model was trained on
Example: JSON Payload for a Model
If your model accepts JSON input, here’s a complete working snippet:
import com.amazonaws.services.sagemaker.model.InvokeEndpointRequest; import com.amazonaws.services.sagemaker.model.InvokeEndpointResult; import java.nio.charset.StandardCharsets; public class SageMakerEndpointCaller { public static void main(String[] args) { // Initialize client (same as step 2) AmazonSageMaker sageMakerClient = AmazonSageMakerClientBuilder.standard() .withRegion("us-east-1") .build(); // Replace with your endpoint's name String endpointName = "your-trained-model-endpoint"; // Prepare payload (match your model's expected input structure) String jsonPayload = "{\"input_features\": [2.3, 4.5, 6.7, 8.9]}"; byte[] payloadBytes = jsonPayload.getBytes(StandardCharsets.UTF_8); // Build the invoke request InvokeEndpointRequest invokeRequest = new InvokeEndpointRequest() .withEndpointName(endpointName) .withContentType("application/json") .withBody(payloadBytes); try { // Send request to the endpoint InvokeEndpointResult response = sageMakerClient.invokeEndpoint(invokeRequest); // Parse and print the response String result = new String(response.getBody().array(), StandardCharsets.UTF_8); System.out.println("Endpoint Response: " + result); } catch (Exception e) { System.err.println("Failed to call endpoint: " + e.getMessage()); e.printStackTrace(); } } }
Critical Things to Keep in Mind
- Payload Matching: Double-check that your request payload matches exactly what your model was trained to process. If you used CSV in your notebook, set
contentTypetotext/csvand pass a comma-separated string as the payload. - IAM Permissions: Ensure the credentials you’re using have the
sagemaker:InvokeEndpointpermission for your target endpoint—otherwise, you’ll get access denied errors. - Region Consistency: The client’s region must match where your endpoint is deployed. Mismatched regions will cause "endpoint not found" errors.
- Error Handling: Add robust exception handling for cases like endpoint downtime, invalid payloads, or service throttling.
内容的提问来源于stack exchange,提问作者theHall

