HttpClient调用WebService(支持账号密码验证)

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());
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章