1. 程式人生 > >java axis呼叫帶有soap頭(soapheader)的.net webservice

java axis呼叫帶有soap頭(soapheader)的.net webservice

有很多同學問我使用axis呼叫.net帶soapheader的webservice是如何實現的,現在貼出程式碼
.net webservice的soap程式碼如下,注意第四行:
<?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:Header>
<AuthHeaderCS xmlns="http://tempuri.org/">
<Username>string</Username>
<Password>string</Password>
</AuthHeaderCS>
</soap:Header>
<soap:Body>
<StarTrans xmlns="http://tempuri.org/" />
</soap:Body>
</soap:Envelope>


java程式碼:
import java.rmi.RemoteException;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import javax.xml.soap.SOAPException;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.message.SOAPHeaderElement;

public class aa
{
public static void main(String[] args) throws ServiceException, RemoteException
{
try
{
// 服務端的url,需要根據情況更改。
String endpointURL = "http://192.168.0.209:7080/DataShareWebService.asmx?wsdl";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new java.net.URL(endpointURL));
call.setSOAPActionURI("http://tempuri.org/" + "StarTrans");
call.setOperationName(new QName("DataShareWebService", "StarTrans"));// 設定操作的名稱。
// 由於需要認證,故需要設定呼叫的使用者名稱和密碼。
SOAPHeaderElement soapHeaderElement = new SOAPHeaderElement("http://tempuri.org/", "AuthHeaderCS");
soapHeaderElement.setNamespaceURI("http://tempuri.org/");
try
{
soapHeaderElement.addChildElement("Username").setValue("admin");
soapHeaderElement.addChildElement("Password").setValue("123");
}
catch (SOAPException e)
{
e.printStackTrace();
}
call.addHeader(soapHeaderElement);
call.setReturnType(XMLType.XSD_STRING);// 返回的資料型別
call.addParameter("op1", XMLType.XSD_STRING, ParameterMode.IN);// 引數的型別
String ret = (String) call.invoke(new Object[] { "11111" });// 執行呼叫
System.out.println(ret);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

第27 28兩行,NamespaceURI要寫兩次,如果不知道你的webservice的NamespaceURI是什麼,就要wsdl裡面去看一下