Knowing nothing of web services, I'm just trying to call some "isAlive" service that is described by a wsdl.
This seems to me like something that should take no more than 2-5 lines of code but I can't seem to find anything but huge long examples involving 3rd party packages etc.
Anyone has any ideas? If it is always suppose to be long maybe a good explanation as to why it has to be so complicated will also be appreciated.
I'm using Eclipse and the wsdl is SOAP.
JDK 6 comes with jax-ws, everything you need to develop a client for a web service.
I'm unable to find some simple enough examples to post , but start at https://jax-ws.dev.java.net/
Edit: here's a simple example - a client for this web service: http://xmethods.com/ve2/ViewListing.po?key=427565
C:\temp> md generated
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\wsimport -keep -d generated http://www50.brinkster.com/vbfacileinpt/np.asmx?wsdl
Create PrimeClient.java which look like:
import javax.xml.ws.WebServiceRef;
import com.microsoft.webservices.*;
//the above namespace is from the generated code from the wsdl.
public class PrimeClient {
//Cant get this to work.. #WebServiceRef(wsdlLocation="http://www50.brinkster.com/vbfacileinpt/np.asmx?wsdl")
static PrimeNumbers service;
public static void main(String[] args) {
try {
service = new PrimeNumbers();
PrimeClient client = new PrimeClient();
client.doTest(args);
} catch(Exception e) {
e.printStackTrace();
}
}
public void doTest(String[] args) {
try {
System.out.println("Retrieving the port from the following service: " + service);
PrimeNumbersSoap pm = service.getPrimeNumbersSoap();
System.out.println("Invoking the getPrimeNumbersSoap operation ");
System.out.println(pm.getPrimeNumbers(100));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Compile and run:
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\javac -cp generated PrimeClient.java
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\java -cp .;generated PrimeClient
Retrieving the port from the following service: com.microsoft.webservices.PrimeN
umbers#19b5393
Invoking the getPrimeNumbersSoap operation
1,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
There are plugins for IDE's which generate the needed code to consume a web service for you.
After the plugin generates you the base methods you simply call a web service like that:
TransportServiceSoap service = new TransportServiceLocator().getTransportServiceSoap();
service.getCities();
Have a look at http://urbas.tk/index.php/2009/02/20/eclipse-plug-in-as-a-web-service-client/
There are three ways to write a web service client
Dynamic proxy
Dynamic invocation interface (DII)
Application client
Example for Dynamic Proxy Client
import java.net.URL;
import javax.xml.rpc.Service;
import javax.xml.rpc.JAXRPCException;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceFactory;
import dynamicproxy.HelloIF;
public class HelloClient {
public static void main(String[] args) {
try {
String UrlString = "Your WSDL URL"; //
String nameSpaceUri = "urn:Foo";
String serviceName = "MyHelloService";
String portName = "HelloIFPort";
System.out.println("UrlString = " + UrlString);
URL helloWsdlUrl = new URL(UrlString);
ServiceFactory serviceFactory =
ServiceFactory.newInstance();
Service helloService =
serviceFactory.createService(helloWsdlUrl,
new QName(nameSpaceUri, serviceName));
dynamicproxy.HelloIF myProxy =
(dynamicproxy.HelloIF)
helloService.getPort(
new QName(nameSpaceUri, portName),
dynamicproxy.HelloIF.class);
System.out.println(myProxy.sayHello("Buzz"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I hope , this would solve your question.
The easiest I've found so far to use is the Idea IntelliJ wizard which - using Metro libraries - generate a very small code snippet which works fine with Java 6.
Related
I was creating a Java web service server, using eclipse IDE. that server is the following.
Note: I am working in UBUNTU
package com.tesis.service;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RejectedExecutionException;
import com.mathworks.engine.*;
/**
* #author root
*
*/
public class CNNPredict
{
public String cNNPredict(int[] Image, int Height, int Width) throws Exception
{
String FilePath = "/home/user/Documents/MATLAB/Project";
char[] CharFilePath = FilePath.toCharArray();
MatlabEngine eng = MatlabEngine.startMatlab();
eng.feval("cd", CharFilePath);
String result = eng.feval("CNNPredict",Image,Height,Width);
return result;
}
}
As you can see I am using MATLAB engine.
Matlab engine documentation. I checked that cNNPredict method is working properly by copying it into a new Java project and It worked perfectly.
I added the .jar files required to run java engine to the Dynamic web project where the web service is located.
Apparently this web service runs without problems Web Service working in local host
If I click on "CnnPredict" link I get the wsdl direction of the class , this direction is what I use to link the client with the server.
this is the client code:
public static void main(String[] args) throws IOException, CNNPredictExceptionException
{
CNNPredictStub stub = new CNNPredictStub();
CNNPredict cnn = new CNNPredict();
BufferedImage img = null;
System.out.println("Reading image ...");
img = ImageIO.read(new File("/home/riosgamarra/Documents/MATLAB/TesisGamarrarios/101_ObjectCategories/laptop/image_0009.jpg"));
int[] UnrolledImage = convertToGray(img);
cnn.setImage(UnrolledImage);
cnn.setWidth(img.getWidth());
cnn.setHeight(img.getHeight());
System.out.println(stub.cNNPredict(cnn).get_return());
}
It has no errors, but when I run it this error message shows up:
Exception in thread "main" org.apache.axis2.AxisFault: <faultstring>com/mathworks/engine/MatlabEngine</faultstring>
at org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Utils.java:513)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:368)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:414)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:150)
at com.tesis.service.CNNPredictStub.cNNPredict(CNNPredictStub.java:197)
at com.tesis.client.CallWS.main(CallWS.java:40)
what I am missing ? do I need to add any special permissions to the server project ? What Am I missing ?
Note: I run the client clicking on the class and selecting Run as > Java application.
at com.tesis.service.CNNPredictStub.cNNPredict(CNNPredictStub.java:197)
is where the exception is but
public class CNNPredict
{
public String cNNPredict(int[] Image, int Height, int Width) throws Exception
{
String FilePath = "/home/user/Documents/MATLAB/Project";
char[] CharFilePath = FilePath.toCharArray();
MatlabEngine eng = MatlabEngine.startMatlab();
eng.feval("cd", CharFilePath);
String result = eng.feval("CNNPredict",Image,Height,Width);
return result;
}
}
is not the stub. First we need to the right code to look at. The matlab api is straight forward. My guess is that the stub is making the wrong call
i have placed the wsdl files in
E:/testworkspace/projectname/docroot
WEB-INF
src
com
test
wsdl
if i give the full path say wsdlLocation = "file:E:/testworkspace/projectname/docroot/WEB- INF/src/com/test/wsdl/some.wsdl" , it picks the WSDL file.
but i need to make generic something like directly fetching:
#WebServiceClient(name = "TestInterfaceService",
wsdlLocation = "WEB-INF/wsdl/some.wsdl",
targetNamespace = "http://www.google.com/job")
public class TestInterfaceService extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://www.google.com/job", "TestInterfaceService");
public final static QName TestInterfaceSoapHttpPort = new QName("http://www.google.com/job", "TestInterfaceSoapHttpPort");
static {
URL url = null;
try {
url = new URL("WEB-INF/wsdl/some.wsdl");
} catch (MalformedURLException e) {
java.util.logging.Logger.getLogger(TestInterfaceService.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "WEB-INF/wsdl/some.wsdl");
}
WSDL_LOCATION = url;
}
Can you please suggest how to pick WSDL files independently from that of my local system, currently it throws the error Can not initialize the default wsdl from WEB-INF/wsdl/some.wsdl
You need a valid URL string to be able to create a new URL. If your service does expose the URL, it might be an option to use that.
If your client is a web application, another option is to make the wsdl available via your application and reference it from there using http://localhost/app/some.wsdl
Hope that helps
Not sure what you are trying to achive here, the configuration: wsdlLocation = "WEB-INF/wsdl/some.wsdl" is perfectly fine as long as WSLD file is under WEB-INF/wsdl, if you placed the wsdl in WEB-INF/src/com/test/wsdl and specifying WSDL location like this: wsdlLocation = "WEB-INF/wsdl/some.wsdl - of course it won't work, add your WSDL in WEB-INF/wsdl and all will be fine.
I needed to write a JavaAgent in a Lotus Notes 6.5 DB to access a web service. I used Axis Apache API for this purpose. I created A Java agent and added the jar files of axis in the agent by using Edit Project button.
Below is the agent code:
import lotus.domino.*;
import javax.xml.*;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import javax.xml.namespace.QName;
import java.net.URL;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
String endpoint = "http://ws.apache.org:5049/axis/services/echo";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new java.net.URL(endpoint) );
call.setOperationName(new QName("http://soapinterop.org/", "echoString"));
String ret = (String) call.invoke( new Object[] { "Hello!" } );
System.out.println("Sent 'Hello!', got '" + ret + "'");
} catch(Exception e) {
e.printStackTrace();
}
}
}
And below is the exception thrown:
java.lang.ExceptionInInitializerError: org.apache.commons.discovery.DiscoveryException: No implementation defined for org.apache.commons.logging.LogFactory
at org.apache.commons.discovery.tools.SPInterface.newInstance(SPInterface.java:197)
at org.apache.commons.discovery.tools.DiscoverClass.newInstance(DiscoverClass.java:579)
at org.apache.commons.discovery.tools.DiscoverSingleton.find(DiscoverSingleton.java:418)
at org.apache.commons.discovery.tools.DiscoverSingleton.find(DiscoverSingleton.java:378)
at org.apache.axis.components.logger.LogFactory$1.run(LogFactory.java:84)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.axis.components.logger.LogFactory.getLogFactory(LogFactory.java:80)
at org.apache.axis.components.logger.LogFactory.<clinit>(LogFactory.java:72)
at org.apache.axis.configuration.EngineConfigurationFactoryFinder.<clinit>(EngineConfigurationFactoryFinder.java:94)
at org.apache.axis.client.Service.<init>(Service.java:111)
at JavaAgent.NotesMain(JavaAgent.java:17)
at lotus.domino.AgentBase.runNotes(Unknown Source)
at lotus.domino.NotesThread.run(NotesThread.java:218)
I thried to follow some links on the internet like, But i was not able to get exactly what it was asking to do. eg: http://www-10.lotus.com/ldd/nd6forum.nsf/55c38d716d632d9b8525689b005ba1c0/40d033fba3897f4d85256cd30034026a?OpenDocument
Any help will be great. All i wanted to do is write an agent so that i can access a web service, say temperature conversion web service on w3schools. http://www.w3schools.com/webservices/tempconvert.asmx?op=FahrenheitToCelsius
I googled with your error message and this is the first hit:
http://croarkin.blogspot.fi/2010/08/commons-logging-headaches-with-axis.html
It suggests using a commons-logging.properties file with:
org.apache.commons.logging.Log = org.apache.commons.logging.impl.Log4JLogger
org.apache.commons.logging.LogFactory = org.apache.commons.logging.impl.LogFactoryImpl
or putting this to your code:
#BeforeClass
public static void beforeClass() {
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.LogFactoryImpl");
}
Probably you've already tried this because it's the first hit with google but just in case...
I have a strange problem.
Using wsimport I generated als JAX-WS Code from a WSDL (in a dedicated eclipse java project). This works fine in JDK6 without any external dependencies (running in Eclipse)
I have second project where I once used Apache CXF. If I copy the Code described in 1.) into this project, suddenly not the JDK executes the JAX-WS stuff (files I generated), but rather Apache CXF.
How can I prevent Apache CXF "running" the JAX-WS stuff. (Problem is, CXF Fails to run the code...). I also completely do not understand how Apache CXF discovers these classes. I did not register them anywere?
Thank you very much!
Markus
Apache CXF (cxf-rt-frontend-jaxws-*.jar to be precise) registers itself as a JAX-WS provider in the JVM. Inside the aforementioned JAR there is a file named: /META-INF/services/javax.xml.ws.spi.Provider with the following contents:
org.apache.cxf.jaxws.spi.ProviderImpl
If you now look at javax.xml.ws.spi.FactoryFinder#find method you will discover that JDK searches the CLASSPATH for the presence of javax.xml.ws.spi.Provider file and falls back to default Sun implementation if not available. So you have two options to force fallback:
either remove cxf-rt-frontend-jaxws-*.jar from CLASSPATH
or override javax.xml.ws.spi.Provider file provided by CXF to point to fallback location
The second option is actually a bit easier. Simply create:
/src/main/resources/META-INF/services/javax.xml.ws.spi.Provider
file (assuming you are using Maven) with the following contents:
org.apache.cxf.jaxws.spi.ProviderImpl
That's it, tested with javax.xml.ws.Endpoint#publish.
For the default implementation put:
com.sun.xml.internal.ws.spi.ProviderImpl
inside /src/main/resources/META-INF/services/javax.xml.ws.spi.Provider
I tried the other and I just couldn't make it work at all, so to set CXF if it was not set to CXF, I just override the delegate inside the service.
try {
loc = this.getClass().getResource(wsdlResource);
QName qName = new QName( wsTargetNamespace, wsName );
service = new YourWS(loc, qName);
Field delegateField = Service.class.getDeclaredField("delegate"); //ALLOW CXF SPECIFIC SERVICE DELEGATE ONLY!
delegateField.setAccessible(true);
ServiceDelegate previousDelegate = (ServiceDelegate) delegateField.get(service);
if (!previousDelegate.getClass().getName().contains("cxf")) {
ServiceDelegate serviceDelegate = ((Provider) Class.forName("org.apache.cxf.jaxws.spi.ProviderImpl").newInstance())
.createServiceDelegate(loc, qName, service.getClass());
log.info("The " + getClass().getSimpleName() + " delegate is changed from " + "[" + previousDelegate + "] to [" +
serviceDelegate +
"]");
delegateField.set(service, serviceDelegate);
}
port = service.getYourWSSoap();
The standard finding mechanisms don't seem to work nicely in OSGi (*).
There are two ways I've gotten to work forcing the service to pick up the CXF implementation of javax.xml.ws.spi.Provider:
the approach of setting delegate by reflection given in EpicPandaForce's answer to this question (https://stackoverflow.com/a/31892305/109079)
calling the lower-level JaxWsProxyFactoryBean; this seems to avoid all calls to the javax.xml.ws.spi.FactoryFinder included with Java which is the root of the problem
Here is an example of the latter, for less intrepid coders who prefer not reflectively changing private fields:
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.getClientFactoryBean().getServiceFactory().setWsdlURL(WinRmService.WSDL_LOCATION);
factory.setServiceName(WinRmService.SERVICE);
factory.setEndpointName(WinRmService.WinRmPort);
// factory.setFeatures(...); // if required
Service winrm = factory.create(WinRm.class);
Client client = ClientProxy.getClient(winrm);
A couple of notes:
Passing a URL as above, rather than the simpler factory.setWsdlURL(String) may be needed if the WSDL is a resource on the classpath (avoid unresolvable bundle://... URLs for classpath items)
You may need additional bundles for features (such as addressing)
(*) As for why the finding mechanisms don't work in most OSGi containers, check out this little bit of nasty in Oracle Java's FactoryFinder:
private static final String OSGI_SERVICE_LOADER_CLASS_NAME = "com.sun.org.glassfish.hk2.osgiresourcelocator.ServiceLoader";
private static boolean isOsgi() {
try {
Class.forName(OSGI_SERVICE_LOADER_CLASS_NAME);
return true;
} catch (ClassNotFoundException ignored) {
}
return false;
}
OSGi = Glassfish? Fishy indeed!
I had a similar problem. In my case I had to use org.apache.cxf.jaxws.spi.ProviderImpl for JAX-WS stuff (creating webservice endpoints etc.) and com.sun.xml.internal.ws.spi.ProviderImpl for publishing endpoints on com.sun.net.httpserver.HttpsServer.
I managed to solve this by creating my own provider which extends javax.xml.ws.spi.Provider and using it instead of the default one.
package provider;
import java.net.URL;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.ws.Endpoint;
import javax.xml.ws.EndpointReference;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.spi.Provider;
import javax.xml.ws.spi.ServiceDelegate;
import javax.xml.ws.wsaddressing.W3CEndpointReference;
import org.w3c.dom.Element;
public class MyProvider extends Provider
{
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public ServiceDelegate createServiceDelegate(URL wsdlDocumentLocation, QName serviceName, Class serviceClass)
{
try {
return ((Provider) Class.forName("org.apache.cxf.jaxws.spi.ProviderImpl").newInstance()).createServiceDelegate(wsdlDocumentLocation, serviceName, serviceClass.getClass());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
public Endpoint createEndpoint(String bindingId, Object implementor)
{
try {
return ((Provider) Class.forName("com.sun.xml.internal.ws.spi.ProviderImpl").newInstance()).createEndpoint(bindingId, implementor);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
public Endpoint createAndPublishEndpoint(String address, Object implementor)
{
try {
return ((Provider) Class.forName("com.sun.xml.internal.ws.spi.ProviderImpl").newInstance()).createAndPublishEndpoint(address, implementor);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
public EndpointReference readEndpointReference(Source eprInfoset)
{
try {
return ((Provider) Class.forName("org.apache.cxf.jaxws.spi.ProviderImpl").newInstance()).readEndpointReference(eprInfoset);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
public <T> T getPort(EndpointReference endpointReference, Class<T> serviceEndpointInterface, WebServiceFeature... features)
{
try {
return ((Provider) Class.forName("org.apache.cxf.jaxws.spi.ProviderImpl").newInstance()).getPort(endpointReference, serviceEndpointInterface, features);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
public W3CEndpointReference createW3CEndpointReference(String address, QName serviceName, QName portName, List<Element> metadata, String wsdlDocumentLocation, List<Element> referenceParameters)
{
try {
return ((Provider) Class.forName("org.apache.cxf.jaxws.spi.ProviderImpl").newInstance()).createW3CEndpointReference(address, serviceName, portName, metadata, wsdlDocumentLocation,
referenceParameters);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Then simply create:
/src/main/resources/META-INF/services/javax.xml.ws.spi.Provider
file (assuming you are using Maven) with the following contents:
package.MyProvider
So I'm running out of ideas to try to actually get a client to connect to the SOAP service I'm running through axis2.
I tried two methods, one was to use wsdl2java to build the stub and associated client side classes, and then write a Client class that build the requests messages and sends them through the Stub. The other way was to use the ServiceClient to connect..
Both are failing in their own way..
Option #1, every time a message is sent through the stub I get this back:
org.apache.axis2.AxisFault: The input stream for an incoming message is null.
at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:87)
at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:67)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:354)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:417)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
Option #2, everytime I run it I get this Exception:
org.apache.axis2.deployment.DeploymentException: org.apache.axis2.transport.local.LocalTransportSender
Option #2 source:
import javax.xml.stream.XMLStreamException;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.Constants;
import org.apache.axis2.client.ServiceClient;
public class loyaltyClient {
private static EndpointReference targetEPR =
new EndpointReference(
"http://localhost:8080/axis2/services/service");
public static OMElement verifyCustomer(String customer_id) {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace(
"http://localhost/", "service");
OMElement method = fac.createOMElement("VerifyCustomer", omNs);
OMElement value1 = fac.createOMElement("customer_id",omNs);
OMElement value2 = fac.createOMElement("source_id",omNs);
OMElement value3 = fac.createOMElement("source_password",omNs);
OMElement value4 = fac.createOMElement("source_txnid",omNs);
OMElement value5 = fac.createOMElement("timestamp",omNs);
value1.addChild(fac.createOMText(value1, customer_id));
value2.addChild(fac.createOMText(value2, "source"));
value3.addChild(fac.createOMText(value3, "1234"));
value4.addChild(fac.createOMText(value4, "123"));
value5.addChild(fac.createOMText(value5, "06-01-2010 12:01:01"));
method.addChild(value1);
method.addChild(value2);
method.addChild(value3);
method.addChild(value4);
method.addChild(value5);
return method;
}
public static void main(String[] args) {
try {
OMElement vctest = loyaltyClient.verifyCustomer("6177740603");
Options options = new Options();
options.setTo(targetEPR);
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
ServiceClient sender = new ServiceClient();
sender.setOptions(options);
OMElement result = sender.sendReceive(vctest);
String response = result.getFirstElement().getText();
System.out.println(response);
} catch (Exception e) { //(XMLStreamException e) {
System.out.println(e.toString());
}
}
}
I've also encountered the error "The input stream for an incoming message is null" while using Axis to connect to a .Net service provider.
The problem is that .Net doesn't not support a feature called "chunked encoding", by default Axis will break its request header in chunks which is suppose to be a HTTP 1.1 compliant thing.
Anyway, you can turn this feature off in Axis by doing the following:
// Turn off the Axsis Chunked feature, some service providers (like .Net) don't support chunked headers.
Options options = serviceClient.getOptions();
options.setProperty(HTTPConstants.CHUNKED, Constants.VALUE_FALSE);
serviceClient.setOptions(options);
This worked for me. Another thing to make sure of when dealing with .Net services is to be able to specify the port name and make sure your message payload has the namespace prefix for each element.
Hope this info helps somebody.
Cheers,
DC
With the caveat that Axis2 is a buggy pile of crap, I recently had to write an Axis2 client, and found that using the default ServiceClient() constructor didn't work well -- I had to manually create a ConfigurationContext, etc. I found that using ServiceClient.getOptions() instead of creating new Options() preserved some default data. I'd also recommend dropping the options.setTransportInProtocol(...) unless you really need it -- everything should work fine via HTTP without this. Also, you may need to set options.setAction(...) to correspond with the "operation" in your WSDL.
I've included the bulk of my client (with sensitive information stripped out), in hopes that it will help. You can probably safely ignore the portions regarding addressing unless you plan to use WS-Addressing.
ConfigurationContext cfgCtx = null;
try {
/* Passing null to both params causes an AxisConfiguration to be created that uses
* the default axis2.xml file, which is included in the axis2 distribution jar.
* This is ideal for our case, since we cannot pass a full file path (relative
* paths are not allowed) because we do not know where the customer will deploy
* the application. This also allows engaging modules from the classpath. */
cfgCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null , null);
} catch (AxisFault e) {
// Bubble up the error
}
ServiceClient svcClient = null;
try {
svcClient = new ServiceClient(cfgCtx, null);
} catch (AxisFault e) {
// Bubble up the error
}
try {
/* This will work with the above ConfigurationContext as long as the module
* (addressing-1.5.1.mar) is on the classpath, e.g. in shared/lib. */
svcClient.engageModule("addressing");
} catch (AxisFault e) {
// Bubble up the error
}
Options opts = svcClient.getOptions();
opts.setTo(new EndpointReference("http://myservername:8080/axis2/services/MyService"));
opts.setAction("urn:doSomething"); // Corresponds to the "operation" in MyService's WSDL
opts.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI); // Set output to SOAP 1.2
SOAPFactory factory = OMAbstractFactory.getSOAP12Factory();
svcClient.addHeader(createSOAPSecurityHeader(factory, response)); // CreateSOAPHeader just creates an OMElement
try {
svcClient.sendReceive(createSOAPBody(factory, response)); // CreateSOAPBody just creates an OMElement
} catch (AxisFault e) {
throw new ResponseDeliveryException(1, "Error sending SOAP payload.", e);
}