java客户端访问.net实现的WebService

    技术2022-05-11  66

    前两天有个同事说他们项目组有个用.net实现的WebService,需要用java客户端访问,让我帮着看看怎么做,正好最近在用axis2,就试了试,虽然最后解决了,但还是稍微碰到了些障碍,特别记录下来以供参考。 .net的WebService是接收两个整数,返回它们的和,描述是这样的,对于.net开发人员来说应该很熟悉: POST /TestWebService1/Service1.asmx HTTP/1.1 Host: XXXX Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://tempuri.org/test" <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">   <soap:Body>     <test xmlns="http://tempuri.org/">       <a>int</a>       <b>int</b>     </test>   </soap:Body> </soap:Envelope> HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">   <soap:Body>     <testResponse xmlns="http://tempuri.org/">       <testResult>int</testResult>     </testResponse>   </soap:Body> </soap:Envelope> 最后的客户端java代码是这样的,需要注意的是红色部分: package sample; 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.Constants; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; public class AXIOMClient {     private static EndpointReference targetEPR =         new EndpointReference("http://XXXX/TestWebService1/Service1.asmx");     public static OMElement getTopTree() {         OMFactory fac = OMAbstractFactory.getOMFactory();                 OMNamespace omNs = fac.createOMNamespace("http://tempuri.org/", "ns");         OMElement method = fac.createOMElement("test", omNs);         OMElement value1 = fac.createOMElement("a", omNs);         value1.addChild(fac.createOMText(value1, "12"));         method.addChild(value1);                  OMElement value2 = fac.createOMElement("b", omNs);         value2.addChild(fac.createOMText(value2, "33"));         method.addChild(value2);                  return method;     }     public static void main(String[] args) {         try {             OMElement getTopTree = getTopTree();             Options options = new Options();             options.setTo(targetEPR);             options.setAction("http://tempuri.org/test");             options.setTransportInProtocol(Constants.TRANSPORT_HTTP);             ServiceClient sender = new ServiceClient();             sender.setOptions(options);             OMElement result = sender.sendReceive(getTopTree);             String response = result.getFirstElement().getText();                          System.err.println("RET: " + response);         } catch (Exception e) {             e.printStackTrace();         }     }      }

    最新回复(0)