1、得到wsdl文件,用soapui解析一下,如下圖:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://server/">
<soapenv:Header/>
<soapenv:Body>
<ser:helloworld><!--helloworld:方法名稱-->
<!--Optional:參數1-->
<arg0>?</arg0>
<!--Optional:參數2-->
<arg1>?</arg1>
</ser:helloworld>
</soapenv:Body>
</soapenv:Envelope>
2、引用包路徑如下
import java.io.InputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
3、封裝以上xml格式的字符串
String content="以上格式的字符串";
// HttpClient發送SOAP請求
int timeout = 10000;
System.out.println("HttpClient 發送SOAP請求");
HttpClient client = new HttpClient();
//如果需要用戶名密碼驗證;不需要驗證登錄則不需要以下4行
String username = "zhangsan";
String password = "123";
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(AuthScope.ANY, creds);
PostMethod postMethod = new PostMethod("http://127.0.0.1:8080/WebServiceDemo/SayHelloPort?wsdl");
// 設置連接超時
client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
// 設置讀取時間超時
client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
// 然後把Soap請求數據添加到PostMethod中
RequestEntity requestEntity = new StringRequestEntity(content,"text/xml", "UTF-8");
// 設置請求頭部,否則可能會報 “no SOAPAction header” 的錯誤
postMethod.setRequestHeader("SOAPAction", "");
// 設置請求體
postMethod.setRequestEntity(requestEntity);
int status = client.executeMethod(postMethod);
if (status == 200) {// 成功
InputStream is = postMethod.getResponseBodyAsStream();
// 獲取請求結果字符串
String result = IOUtils.toString(is);
System.out.println("返回結果:"+result);
} else {
System.out.println("錯誤代碼:"+status+":"+postMethod.getResponseBodyAsString());
}