Java用戶端調用.NET的WebService,.netwebservice
項目需要去調用.NET的WebSrevice,本身是Java,研究了半天,終於有些頭緒,記下來。
1,建立.NET WebService。只在原方法上加上一個string類型的參數str
[WebMethod] public string HelloWorld(string str) { return "Hello World"; }
2,建立Java的WebService用戶端,lib引入以下5個jar包(我是用idea產生的WebService用戶端,會下載7個包,我試著刪掉了log4j和saaj兩個包也能正常運行)
import org.apache.axis.client.Call;import org.apache.axis.client.Service;import org.apache.axis.encoding.XMLType;import javax.xml.namespace.QName;import javax.xml.rpc.ParameterMode;public class HelloWorldClient { public static void main(String[] argv) { String endpoint ="http://localhost:64662/WebService1.asmx?wsdl"; try { // 定義服務 Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress(endpoint); call.setOperationName(new QName("http://tempuri.org/", "HelloWorld")); call.setSOAPActionURI("http://tempuri.org/HelloWorld"); call.addParameter(new QName("http://tempuri.org/", "str"),// 這裡的str對應webservice參數名稱 XMLType.SOAP_STRING, ParameterMode.IN); call.setReturnType(XMLType.SOAP_STRING); String retVal1 = (String) call.invoke(new Object[] {"Hello World!"}); System.out.println(retVal1); } catch (Exception e) { e.printStackTrace(); } }}
註:1,網上看到有直接寫成call.setOperationName("HelloWorld"),我試過不行。不知道是不是跨語言的原因。
2,網上也看到省略call.setSOAPActionURI這 一句的,但我的報錯了。
3,其實項目的WebService裡面用的參數是實體,我試著Java端通過XMLType.XSD_ANYTYPE類型傳實體過去,結果說類型沒註冊之類的。網上看有方案比較繁瑣,倒不如將實體序列化成Json串傳過去省事。
4,參數的命名空間參見服務頁面