You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AWS Java SDK连接SageMaker并调用Jupyter Notebook创建的端点?

Using AWS Java SDK to Connect to Amazon SageMaker and Call an Existing Endpoint

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_ID and AWS_SECRET_ACCESS_KEY)
  • The ~/.aws/credentials file 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 contentType to text/csv and pass a comma-separated string as the payload.
  • IAM Permissions: Ensure the credentials you’re using have the sagemaker:InvokeEndpoint permission 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:03:16