httpclient 访问 webservice(转)
转载自:http://blog.csdn.net/yang382197207/article/details/14227347
通过httpclient访问已经部署好的webservice,webservice的创建和部署通过axis2完成,参考
Axis2 Eclipse 开发webservice(2)http://blog.csdn.net/yang382197207/article/details/14124533
在axis2-1.6.0的lib文件夹下面已经包含了httpclient相关的jar包:commons-codec-1.3.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar,log4j-1.2.15.jar
新建项目,导入上述包,创建两个文件HelloWordTest.java和HelloWordTest2.java,来访问部署的tomcat下的axis服务HelloWord
其中SOAP请求可以通过软件来定义,参考编写,推挤两款软件:SOAPUI和XMLSPY
通过soapUI来定义SOAP请求
打开SOAPUI,新建New SOAP Project,输入项目name,在Initial WSDL中填写服务的地址,这里填写HelloWord服务的WSDL地址。
点击OK。项目建立好如下,点击下面的Request 1
出现有图所示,就是SOAP请求数据,给name赋值Yang
点击下图上面的三角,可以对SOAP请求进行测试,结果如下
在XMLSpy中建立SOAP请求也很方便,直接在SOAP菜单下选择Creat SOAP Request,XMLSPY也提供了send request to server命令进行SOAP请求的测试。
根据上述建立的SOAP请求,创建在java中的SOAP请求数据。
public class WebServiceTest {
public static String buildReqSoapData() throws IOException {
// Create a StringEntity for the SOAP XML.
byte[] bytes = FileUtils.readFileToByteArray(new File("d:/template.docx"));
String wordByte=Base64.encodeBase64String(bytes);
String str = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\">"
+ "<soap:Header/>"
+ "<soap:Body>"
+ "<tem:WordToPDFReturnByteStream>"
+ "<tem:wordByte>"
+ wordByte
+ "</tem:wordByte>"
+ "</tem:WordToPDFReturnByteStream>"
+ "</soap:Body>" + "</soap:Envelope>";
return str;
}
public static void main(String[] args) throws Exception{
HttpClient client = HttpClients.createDefault();
String reqSoapData = buildReqSoapData();
HttpPost post = new HttpPost("http://10.255.33.27:8099/WordToPDF.asmx?wsdl");
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 (Exception e) {
e.printStackTrace();
}
}
}
获得响应后可解析xml获取最终的结果。
浙公网安备 33010602011771号