Of course! Consuming a SAP Web Service from Java is a very common enterprise integration task. This guide will walk you through the entire process, from finding the service in SAP to writing the Java code.

We'll cover two primary methods:
- The Modern Approach (Recommended): Using JAX-WS with a WSDL file. This is the most common, robust, and type-safe method.
- The Lightweight Approach: Using a RESTful API (OData). Many modern SAP systems expose data as REST services, which can be easier to work with.
Prerequisites
Before you start, you need a few things:
- Access to a SAP System: You need a user ID and password with the necessary permissions to access the web service.
- The WSDL (for SOAP) or OData Service URL (for REST): This is the "address" of the service. We'll cover how to find this in SAP.
- Java Development Kit (JDK): Version 8 or newer.
- An IDE: IntelliJ IDEA or Eclipse are excellent choices.
- Build Tool: Maven or Gradle (we'll use Maven in this example).
Part 1: Consuming a SOAP Web Service (JAX-WS)
This is the traditional way to interact with SAP, often using the SAP NetWeaver Gateway service or a custom-developed SOAP service.
Step 1: Find the WSDL in SAP
- Log in to your SAP system using the SAP GUI.
- Use the transaction code
SOAMANAGERto open the "Enterprise Services Browser". - Navigate to the service you want to consume. You can search by service name.
- Select your service and click on the "WSDL" button. This will generate the WSDL (Web Services Description Language) file.
- Copy the URL of the WSDL file from your browser's address bar. It will look something like this:
https://<your-sap-system>:<port>/sap/bc/srt/wsdl/srvc_URL_8A5B2D915357D7A9E10000000A4210A4/wsdl11/allinone/ws_policy_document?wsdl=1
Step 2: Generate Java Client Code from WSDL
The best practice is to use the wsimport tool that comes with the JDK. This tool reads the WSDL and generates all the necessary Java classes (stubs, service endpoints, data types) that you can use to call the service.

-
Open a terminal or command prompt.
-
Run the
wsimportcommand, pointing it to the WSDL URL you copied. It's a good idea to put the generated code in its own directory.# Create a directory for the generated code mkdir sap-client-classes cd sap-client-classes # Run wsimport # -keep: Keep the generated source files # -d .: Generate compiled classes in the current directory # -p com.example.sap.generated: The package name for the generated classes wsimport -keep -d . -p com.example.sap.generated "YOUR_SAP_WSDL_URL_HERE"
-
After the command runs, you will have a
com/example/sap/generateddirectory containing.javaand.classfiles.
Step 3: Create a Java Project and Add Dependencies
-
Create a new Maven project in your IDE.
(图片来源网络,侵删) -
Add the generated JAR files to your project's classpath.
- In your IDE, right-click on the project -> Build Path / Modules -> Add External JARs...
- Navigate to the
sap-client-classesdirectory and add all the.jarfiles generated bywsimport.
-
Alternatively, if you want to automate this, you can use a Maven plugin like the JAX-WS Maven Plugin to generate the client code during the build process. This is the preferred approach for CI/CD.
pom.xml example with JAX-WS Plugin:
<project ...> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!-- No explicit dependency needed, wsimport generates it --> </dependencies> <build> <plugins> <plugin> <groupId>org.jvnet.jax-ws-commons</groupId> <artifactId>jaxws-maven-plugin</artifactId> <version>2.3</version> <executions> <execution> <goals> <goal>wsimport</goal> </goals> <configuration> <wsdlUrls> <!-- Put your WSDL URL here --> <wsdlUrl>YOUR_SAP_WSDL_URL_HERE</wsdlUrl> </wsdlUrls> <sourceDestDir>src/main/java</sourceDestDir> <packageName>com.example.sap.generated</packageName> <keep>true</keep> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>Running
mvn clean installwill now generate the client code insrc/main/java.
Step 4: Write the Java Code to Call the Service
Now you can write the Java code to use the generated client. You'll need to handle authentication, which is typically done via a SOAP header.
import com.example.sap.generated.YourServiceName; // Replace with your actual service class name
import com.example.sap.generated.YourServiceNameService; // Replace with your actual service locator
import com.example.sap.generated.YourRequestType; // Replace with your request data type
import com.example.sap.generated.YourResponseType; // Replace with your response data type
import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.MessageContext;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class SapWebServiceClient {
public static void main(String[] args) {
try {
// 1. Create a Service instance from the generated WSDL classes
URL wsdlUrl = new URL("YOUR_SAP_WSDL_URL_HERE");
QName qname = new QName("http://sap.com/xi/SAPGlobal20/...", "YourServiceName"); // Namespace and service name from WSDL
YourServiceNameService service = new YourServiceNameService(wsdlUrl, qname);
// 2. Get the Port (the interface for the web service operations)
YourServiceName port = service.getYourServiceNamePort(); // get...Port method name varies
// 3. Set credentials and endpoint URL
Map<String, Object> requestContext = ((BindingProvider) port).getRequestContext();
// SAP System endpoint URL (can be found in the WSDL or SOAMANAGER)
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://<your-sap-system>:<port>/sap/xi/path/to/service");
// Basic Authentication
String authString = "YOUR_SAP_USERNAME" + ":" + "YOUR_SAP_PASSWORD";
String encodedAuth = Base64.getEncoder().encodeToString(authString.getBytes("UTF-8"));
requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, new HashMap<String, List<String>>() {{
put("Authorization", Collections.singletonList("Basic " + encodedAuth));
}});
// --- OR (often more reliable for SAP) using a SOAP Header ---
// This is a more robust way to handle SAP's authentication mechanisms.
// You might need to use a handler or interceptors for complex scenarios.
// For simple Basic Auth, the above method is often sufficient.
// Example of adding a SOAP header programmatically:
/*
BindingProvider bp = (BindingProvider) port;
SOAPBinding soapBinding = (SOAPBinding) bp.getBinding();
soapBinding.setHandlerChain(Arrays.asList(new CustomSOAPHandler()));
*/
// 4. Prepare and execute the web service call
// This is a placeholder. You need to replace 'yourOperation' with the actual
// operation name and create the correct request object.
YourRequestType request = new YourRequestType();
// ... populate request object with data ...
System.out.println("Calling SAP web service...");
YourResponseType response = port.yourOperation(request); // Replace with your actual operation name
// 5. Process the response
System.out.println("Service call successful!");
System.out.println("Response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Part 2: Consuming a RESTful Web Service (OData)
SAP NetWeaver Gateway makes it easy to expose data as OData services, which are REST-based. This is often simpler than SOAP.
Step 1: Find the OData Service URL in SAP
- Log in to SAP GUI.
- Use transaction
SEGWto open the Gateway Service Builder. - Find your service or create a new one from a data
