webservice系列教學(4)-如何調用webservice(pb,java)
來源:互聯網
上載者:User
web 4.1 使用PowerBuilder調用
適用版本8.0 需下載Bulletin Web Services Toolkit 4.1
4.2使用java調用
需要下載apache soap。下載地址:http://xml.apache.org/soap/index.html
匯入:
import org.apache.soap.*;
import org.apache.soap.rpc.*;
常式:
import java.io.*;
import java.util.*;
import java.net.*;
import org.w3c.dom.*;
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.encoding.*;
import org.apache.soap.encoding.soapenc.*;
import org.apache.soap.rpc.*;
import org.apache.soap.transport.http.SOAPHTTPConnection;
public class testClient {
public static void main(String[] args) throws Exception {
URL url = new URL ("http://192.168.0.4/yundan/service1.wsdl");
//改成你的地址
SOAPMappingRegistry smr = new SOAPMappingRegistry ();
StringDeserializer sd = new StringDeserializer ();
smr.mapTypes (Constants.NS_URI_SOAP_ENC, new QName ("", "Result"), null, null, sd);
// 建立傳輸路徑和參數
SOAPHTTPConnection st = new SOAPHTTPConnection();
// 建立調用
Call call = new Call ();
call.setSOAPTransport(st);
call.setSOAPMappingRegistry (smr);
call.setTargetObjectURI ("http://tempuri.org/message/");
call.setMethodName("addNumbers");
call.setEncodingStyleURI ("http://schemas.xmlsoap.org/soap/encoding/");
Vector params = new Vector();
params.addElement(new Parameter("NumberOne", Double.class, "10", null));
params.addElement(new Parameter("NumberTwo", Double.class, "25", null));
call.setParams(params);
Response resp = null;
try {
resp = call.invoke (url, "http://tempuri.org/action/Hello2.addNumbers");
}
catch (SOAPException e) {
System.err.println("Caught SOAPException (" + e.getFaultCode () + "): " + e.getMessage ());
return;
}
// 檢查傳回值
if (resp != null && !resp.generatedFault()) {
Parameter ret = resp.getReturnValue();
Object value = ret.getValue();
System.out.println ("Answer--> " + value);
}
else {
Fault fault = resp.getFault ();
System.err.println ("Generated fault: ");
System.out.println (" Fault Code = " + fault.getFaultCode());
System.out.println (" Fault String = " + fault.getFaultString());
}
}
}