Java Example of Creating a vSphere Web Services Session
Last Updated December 16, 2024

This example is based on the code in the
VapiAuthenticationHelper.java
and
VimUtil.java
samples.
This example uses the steps that are described in the Create a Web Services Session procedure.
For a complete and up-to-date version of the Java sample code, see the
vsphere-automation-sdk-java
VMware repository at GitHub.
... // Log in to the vSphere Web Services endpoint and retrieve a session identifier. SamlTokenElement tokenElement = ssoConnection.getSamlBearerTokenElement(); String sessionId = LoginByTokenSample.LoginUsingSAMLToken(tokenElement, vimUrl, null, null); // Use the VimPortType and VimService objects from // the vSphere Web Services API for accessing Web Services and // retrieve the request context. VimService vimService = new VimService(); vimPortType vimPort = vimService.getVimPort(); // Add the retrieved session ID to the request context. Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext(); ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, vimUrl); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true); Map<String, List<String>> headers = (Map<String, List<String>>) ctxt.getMessageContext.HTTP_REQUEST_HEADERS); if (headers == null) { headers = new HashMap<String, List<String>>(); } headers.put(“Cookie”, Arrays.asList(vcSessionId); ctxt.put(MessageContext.HTTP_REQUEST_HEADERS, headers); // Use the session ID context when retrieving the ServiceContent object. // The ServiceContent object gives you access to a number of // server-side managed objects that represent vSphere services and components. // For more information about the vSphere Web Services, // see the vSphere Web Services SDK Programming Guide documentation.
ServiceContent serviceContent = VimUtil.getServiceContent(vimPort);