首先下载HttpClient 4.3.1的jar包,下载地址:http://mirrors.hust.edu.cn/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.3.1-bin.zip。
依赖Jar包文件:commons-codec-1.6.jar,httpclient-4.3.1.jar,httpcore-4.3.jar,另外,需要额外加入log4j-1.2.16.jar及commons-logging-1.1.3.jar包。
示例代码如下:
package com.project.ws;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class WSClient {
public static final String WSDLURL = "http://127.0.0.1:8080/Test.asmx?wsdl";
public static void main(String[] args){
HttpClient client = HttpClients.createDefault();
String reqSoapData = buildReqSoapData();
HttpPost post = new HttpPost(WSDLURL);
try {
HttpEntity re = new StringEntity(reqSoapData,"UTF-8");
post.setHeader("Content-Type","application/soap+xml; charset=UTF-8");
//post.setHeader("Content-Length", String.valueOf(reqSoapData.length()));
post.setEntity(re);
HttpResponse response = client.execute(post);
System.out.println("请求服务的Soap文本:"+EntityUtils.toString(post.getEntity()));
System.out.println("请求服务结果状态:"+response.getStatusLine());
System.out.println("请求服务返回XML文本:"+EntityUtils.toString(response.getEntity()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 生成请求服务的Soap XML字符串
* @return String
*/
public static String buildReqSoapData(){
String soapData = "";
soapData += "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" +
"<soap12:Body>" +
" <getStudentInfo xmlns=\"http://tempuri.org/\">" +
" <strKey>person</strKey>" +
" <strwhere>name='花无影'</strwhere>" +
"</getStudentInfo>" +
" </soap12:Body>" +
"</soap12:Envelope>" ;
return soapData;
}
}
说明:其中生成请求的Soap文本中,
<getStudentInfo xmlns="http://tempuri.org/">
<strKey>person</strKey>
<strwhere>name='花无影'</strwhere>
</getStudentInfo>,
getStudentInfo为方法名称,strKey及strwhere为参数名称,对应的值为参数的值。