---
title: "httpclient妙用一 httpclient作为客户端调用webservice"
author: "thinkerAndThinker"
date: "2017-07-17T19:56:24Z"
tags: []
categories: ["企业架构"]
slug: "httpclient-httpclient-webservice"
draft: false
lastmod: "2017-07-17T19:56:24Z"
id: 2384240
url: "https://javatea.iteye.com/blog/2384240"
---

## 1.个人观点

      webservice框架有很多，比如axis、axis2、cxf、xFire等等，做服务端和做客户端都可行，个人感觉使用这些框架的好处是减少了对于接口信息的解析，最主要的是减少了对于传递于网络中XML的解析，代价是你不得不在你的框架中添加对于这些框架的依赖。**个人观点是：服务端使用这些框架还行，如果做客户端，没必要使用这些框架，只需使用httpclient即可。**

## []()2.需求场景

     已经拿到对于接口的描述文件WebServiceFromB.wsdl，需要建立客户端进行调用，WebServiceFromB.wsdl内容如下：

**\[xml]** [view plain](http://blog.csdn.net/zilong_zilong/article/details/53932667 "view plain") [copy](http://blog.csdn.net/zilong_zilong/article/details/53932667 "copy")

 

 [print](http://blog.csdn.net/zilong_zilong/article/details/53932667 "print")[?](http://blog.csdn.net/zilong_zilong/article/details/53932667 "?")

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;wsdl:definitions targetNamespace="http://webservices.b.com" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://webservices.b.com" xmlns:intf="http://webservices.b.com" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
03. &lt;!--WSDL created by Apache Axis version: 1.4
04. Built on Apr 22, 2006 (06:55:48 PDT)--&gt;
05. &lt;wsdl:types&gt;
06. &lt;schema targetNamespace="http://webservices.b.com" xmlns="http://www.w3.org/2001/XMLSchema"&gt;
07. &lt;import namespace="http://schemas.xmlsoap.org/soap/encoding/"/&gt;
08. &lt;complexType name="OrderRequest"&gt;
09. &lt;sequence&gt;
10. &lt;element name="mobile" nillable="true" type="soapenc:string"/&gt;
11. &lt;element name="orderStatus" type="xsd:int"/&gt;
12. &lt;element name="productCode" nillable="true" type="soapenc:string"/&gt;
13. &lt;/sequence&gt;
14. &lt;/complexType&gt;
15. &lt;complexType name="OrderResponse"&gt;
16. &lt;sequence&gt;
17. &lt;element name="status" type="xsd:int"/&gt;
18. &lt;/sequence&gt;
19. &lt;/complexType&gt;
20. &lt;complexType name="QueryRequest"&gt;
21. &lt;sequence&gt;
22. &lt;element name="endTime" nillable="true" type="xsd:dateTime"/&gt;
23. &lt;element name="mobile" nillable="true" type="soapenc:string"/&gt;
24. &lt;element name="startTime" nillable="true" type="xsd:dateTime"/&gt;
25. &lt;/sequence&gt;
26. &lt;/complexType&gt;
27. &lt;complexType name="QueryResponse"&gt;
28. &lt;sequence&gt;
29. &lt;element name="product" nillable="true" type="soapenc:string"/&gt;
30. &lt;element name="status" type="xsd:int"/&gt;
31. &lt;/sequence&gt;
32. &lt;/complexType&gt;
33. &lt;/schema&gt;
34. &lt;/wsdl:types&gt;
35. &lt;wsdl:message name="queryRequest"&gt;
36. &lt;wsdl:part name="in0" type="impl:QueryRequest"/&gt;
37. &lt;/wsdl:message&gt;
38. &lt;wsdl:message name="orderResponse"&gt;
39. &lt;wsdl:part name="orderReturn" type="impl:OrderResponse"/&gt;
40. &lt;/wsdl:message&gt;
41. &lt;wsdl:message name="queryResponse"&gt;
42. &lt;wsdl:part name="queryReturn" type="impl:QueryResponse"/&gt;
43. &lt;/wsdl:message&gt;
44. &lt;wsdl:message name="orderRequest"&gt;
45. &lt;wsdl:part name="in0" type="impl:OrderRequest"/&gt;
46. &lt;/wsdl:message&gt;
47. &lt;wsdl:portType name="WebServiceFromB"&gt;
48. &lt;wsdl:operation name="order" parameterOrder="in0"&gt;
49. &lt;wsdl:input message="impl:orderRequest" name="orderRequest"/&gt;
50. &lt;wsdl:output message="impl:orderResponse" name="orderResponse"/&gt;
51. &lt;/wsdl:operation&gt;
52. &lt;wsdl:operation name="query" parameterOrder="in0"&gt;
53. &lt;wsdl:input message="impl:queryRequest" name="queryRequest"/&gt;
54. &lt;wsdl:output message="impl:queryResponse" name="queryResponse"/&gt;
55. &lt;/wsdl:operation&gt;
56. &lt;/wsdl:portType&gt;
57. &lt;wsdl:binding name="WebServiceFromBSoapBinding" type="impl:WebServiceFromB"&gt;
58. &lt;wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/&gt;
59. &lt;wsdl:operation name="order"&gt;
60. &lt;wsdlsoap:operation soapAction=""/&gt;
61. &lt;wsdl:input name="orderRequest"&gt;
62. &lt;wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://webservices.b.com" use="encoded"/&gt;
63. &lt;/wsdl:input&gt;
64. &lt;wsdl:output name="orderResponse"&gt;
65. &lt;wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://webservices.b.com" use="encoded"/&gt;
66. &lt;/wsdl:output&gt;
67. &lt;/wsdl:operation&gt;
68. &lt;wsdl:operation name="query"&gt;
69. &lt;wsdlsoap:operation soapAction=""/&gt;
70. &lt;wsdl:input name="queryRequest"&gt;
71. &lt;wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://webservices.b.com" use="encoded"/&gt;
72. &lt;/wsdl:input&gt;
73. &lt;wsdl:output name="queryResponse"&gt;
74. &lt;wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://webservices.b.com" use="encoded"/&gt;
75. &lt;/wsdl:output&gt;
76. &lt;/wsdl:operation&gt;
77. &lt;/wsdl:binding&gt;
78. &lt;wsdl:service name="WebServiceFromBService"&gt;
79. &lt;wsdl:port binding="impl:WebServiceFromBSoapBinding" name="WebServiceFromB"&gt;
80. &lt;wsdlsoap:address location="http://localhost:8080/services/WebServiceFromB"/&gt;
81. &lt;/wsdl:port&gt;
82. &lt;/wsdl:service&gt;
83. &lt;/wsdl:definitions&gt;

## []()     3.获取调用报文

        1.首先得安装soapUI 4.5.2,安装后打开，截图如下：

![](http://dl2.iteye.com/upload/attachment/0109/8832/1862acf4-c143-3300-b253-1d2438cdd40f.jpg)  
     

      2.右键点击“Projects”创建工程，截图如下：

![](http://dl2.iteye.com/upload/attachment/0109/8834/c1579289-8832-33f0-bc0c-8039be25234b.jpg)  
     

        3.双击展开左侧创建的工程下所有节点，最后双击“Request 1”节点，在右侧即可拿到soap格式消息，这个就是我们后面作为客户端调用服务端的报文内容，截图如下：

![](http://dl2.iteye.com/upload/attachment/0109/8836/c159790e-3618-3bdd-805b-3a2f53117969.png)  
        拿到的调用order的soap消息为：

 

**\[xml]** [view plain](http://blog.csdn.net/zilong_zilong/article/details/53932667 "view plain") [copy](http://blog.csdn.net/zilong_zilong/article/details/53932667 "copy")

 

 [print](http://blog.csdn.net/zilong_zilong/article/details/53932667 "print")[?](http://blog.csdn.net/zilong_zilong/article/details/53932667 "?")

01. &lt;soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservices.b.com"&gt;
02. &lt;soapenv:Header/&gt;
03. &lt;soapenv:Body&gt;
04. &lt;web:order soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"&gt;
05. &lt;in0 xsi:type="web:OrderRequest"&gt;
06. &lt;mobile xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"&gt;?&lt;/mobile&gt;
07. &lt;orderStatus xsi:type="xsd:int"&gt;?&lt;/orderStatus&gt;
08. &lt;productCode xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"&gt;?&lt;/productCode&gt;
09. &lt;/in0&gt;
10. &lt;/web:order&gt;
11. &lt;/soapenv:Body&gt;
12. &lt;/soapenv:Envelope&gt;

 

 

    拿到的调用query的soap消息为：

 

**\[xml]** [view plain](http://blog.csdn.net/zilong_zilong/article/details/53932667 "view plain") [copy](http://blog.csdn.net/zilong_zilong/article/details/53932667 "copy")

 

 [print](http://blog.csdn.net/zilong_zilong/article/details/53932667 "print")[?](http://blog.csdn.net/zilong_zilong/article/details/53932667 "?")

01. &lt;soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservices.b.com"&gt;
02. &lt;soapenv:Header/&gt;
03. &lt;soapenv:Body&gt;
04. &lt;web:query soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"&gt;
05. &lt;in0 xsi:type="web:QueryRequest"&gt;
06. &lt;endTime xsi:type="xsd:dateTime"&gt;?&lt;/endTime&gt;
07. &lt;mobile xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"&gt;?&lt;/mobile&gt;
08. &lt;startTime xsi:type="xsd:dateTime"&gt;?&lt;/startTime&gt;
09. &lt;/in0&gt;
10. &lt;/web:query&gt;
11. &lt;/soapenv:Body&gt;
12. &lt;/soapenv:Envelope&gt;

    

 

## []() 4.用httpclient发送soap消息

   直接上代码，代码如下：

 

**\[java]** [view plain](http://blog.csdn.net/zilong_zilong/article/details/53932667 "view plain") [copy](http://blog.csdn.net/zilong_zilong/article/details/53932667 "copy")

 

 [print](http://blog.csdn.net/zilong_zilong/article/details/53932667 "print")[?](http://blog.csdn.net/zilong_zilong/article/details/53932667 "?")

001. import java.nio.charset.Charset;
002. import org.apache.http.HttpEntity;
003. import org.apache.http.client.config.RequestConfig;
004. import org.apache.http.client.methods.CloseableHttpResponse;
005. import org.apache.http.client.methods.HttpPost;
006. import org.apache.http.entity.StringEntity;
007. import org.apache.http.impl.client.CloseableHttpClient;
008. import org.apache.http.impl.client.HttpClientBuilder;
009. import org.apache.http.util.EntityUtils;
010. import org.apache.log4j.Logger;
011. public class HttpClientCallSoapUtil {
012. static int socketTimeout = 30000;// 请求超时时间
013. static int connectTimeout = 30000;// 传输超时时间
014. static Logger logger = Logger.getLogger(HttpClientCallSoapUtil.class);
015. /\**
016. * 使用SOAP1.1发送消息
017. \*
018. * @param postUrl
019. * @param soapXml
020. * @param soapAction
021. * @return
022. \*/
023. public static String doPostSoap1\_1(String postUrl, String soapXml,
024. String soapAction) {
025. String retStr = "";
026. // 创建HttpClientBuilder
027. HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
028. // HttpClient
029. CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
030. HttpPost httpPost = new HttpPost(postUrl);
031. //  设置请求和传输超时时间
032. RequestConfig requestConfig = RequestConfig.custom()
033. .setSocketTimeout(socketTimeout)
034. .setConnectTimeout(connectTimeout).build();
035. httpPost.setConfig(requestConfig);
036. try {
037. httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
038. httpPost.setHeader("SOAPAction", soapAction);
039. StringEntity data = new StringEntity(soapXml,
040. Charset.forName("UTF-8"));
041. httpPost.setEntity(data);
042. CloseableHttpResponse response = closeableHttpClient
043. .execute(httpPost);
044. HttpEntity httpEntity = response.getEntity();
045. if (httpEntity != null) {
046. // 打印响应内容
047. retStr = EntityUtils.toString(httpEntity, "UTF-8");
048. logger.info("response:" + retStr);
049. }
050. // 释放资源
051. closeableHttpClient.close();
052. } catch (Exception e) {
053. logger.error("exception in doPostSoap1\_1", e);
054. }
055. return retStr;
056. }
057. /\**
058. * 使用SOAP1.2发送消息
059. \*
060. * @param postUrl
061. * @param soapXml
062. * @param soapAction
063. * @return
064. \*/
065. public static String doPostSoap1\_2(String postUrl, String soapXml,
066. String soapAction) {
067. String retStr = "";
068. // 创建HttpClientBuilder
069. HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
070. // HttpClient
071. CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
072. HttpPost httpPost = new HttpPost(postUrl);
073. // 设置请求和传输超时时间
074. RequestConfig requestConfig = RequestConfig.custom()
075. .setSocketTimeout(socketTimeout)
076. .setConnectTimeout(connectTimeout).build();
077. httpPost.setConfig(requestConfig);
078. try {
079. httpPost.setHeader("Content-Type",
080. "application/soap+xml;charset=UTF-8");
081. httpPost.setHeader("SOAPAction", soapAction);
082. StringEntity data = new StringEntity(soapXml,
083. Charset.forName("UTF-8"));
084. httpPost.setEntity(data);
085. CloseableHttpResponse response = closeableHttpClient
086. .execute(httpPost);
087. HttpEntity httpEntity = response.getEntity();
088. if (httpEntity != null) {
089. // 打印响应内容
090. retStr = EntityUtils.toString(httpEntity, "UTF-8");
091. logger.info("response:" + retStr);
092. }
093. // 释放资源
094. closeableHttpClient.close();
095. } catch (Exception e) {
096. logger.error("exception in doPostSoap1\_2", e);
097. }
098. return retStr;
099. }
100. public static void main(String\[] args) {
101. String orderSoapXml = "&lt;?xml version = \\"1.0\\" ?&gt;"
102. + "&lt;soapenv:Envelope xmlns:xsi=\\"http://www.w3.org/2001/XMLSchema-instance\\" xmlns:xsd=\\"http://www.w3.org/2001/XMLSchema\\" xmlns:soapenv=\\"http://schemas.xmlsoap.org/soap/envelope/\\" xmlns:web=\\"http://webservices.b.com\\"&gt;"
103. + "   &lt;soapenv:Header/&gt;"
104. + "   &lt;soapenv:Body&gt;"
105. + "      &lt;web:order soapenv:encodingStyle=\\"http://schemas.xmlsoap.org/soap/encoding/\\"&gt;"
106. + "         &lt;in0 xsi:type=\\"web:OrderRequest\\"&gt;"
107. + "            &lt;mobile xsi:type=\\"soapenc:string\\" xmlns:soapenc=\\"http://schemas.xmlsoap.org/soap/encoding/\\"&gt;?&lt;/mobile&gt;"
108. + "            &lt;orderStatus xsi:type=\\"xsd:int\\"&gt;?&lt;/orderStatus&gt;"
109. + "            &lt;productCode xsi:type=\\"soapenc:string\\" xmlns:soapenc=\\"http://schemas.xmlsoap.org/soap/encoding/\\"&gt;?&lt;/productCode&gt;"
110. + "         &lt;/in0&gt;" + "      &lt;/web:order&gt;"
111. + "   &lt;/soapenv:Body&gt;" + "&lt;/soapenv:Envelope&gt;";
112. String querySoapXml = "&lt;?xml version = \\"1.0\\" ?&gt;"
113. + "&lt;soapenv:Envelope xmlns:xsi=\\"http://www.w3.org/2001/XMLSchema-instance\\" xmlns:xsd=\\"http://www.w3.org/2001/XMLSchema\\" xmlns:soapenv=\\"http://schemas.xmlsoap.org/soap/envelope/\\" xmlns:web=\\"http://webservices.b.com\\"&gt;"
114. + "   &lt;soapenv:Header/&gt;"
115. + "   &lt;soapenv:Body&gt;"
116. + "      &lt;web:query soapenv:encodingStyle=\\"http://schemas.xmlsoap.org/soap/encoding/\\"&gt;"
117. + "         &lt;in0 xsi:type=\\"web:QueryRequest\\"&gt;"
118. + "            &lt;endTime xsi:type=\\"xsd:dateTime\\"&gt;?&lt;/endTime&gt;"
119. + "            &lt;mobile xsi:type=\\"soapenc:string\\" xmlns:soapenc=\\"http://schemas.xmlsoap.org/soap/encoding/\\"&gt;?&lt;/mobile&gt;"
120. + "            &lt;startTime xsi:type=\\"xsd:dateTime\\"&gt;?&lt;/startTime&gt;"
121. + "         &lt;/in0&gt;" + "      &lt;/web:query&gt;"
122. + "   &lt;/soapenv:Body&gt;" + "&lt;/soapenv:Envelope&gt;";
123. String postUrl = "http://localhost:8080/services/WebServiceFromB";
124. //采用SOAP1.1调用服务端，这种方式能调用服务端为soap1.1和soap1.2的服务
125. doPostSoap1\_1(postUrl, orderSoapXml, "");
126. doPostSoap1\_1(postUrl, querySoapXml, "");
127. //采用SOAP1.2调用服务端，这种方式只能调用服务端为soap1.2的服务
128. //doPostSoap1\_2(postUrl, orderSoapXml, "order");
129. //doPostSoap1\_2(postUrl, querySoapXml, "query");
130. }
131. }

 

## []() 5.总结

       优点：

       1.使用httpclient作为客户端调用webservice，不用关注繁琐的webservice框架，只需找到SOAP消息格式，添加httpclient依赖就行。

       2.使用httpclient调用webservice，建议采用soap1.1方式调用，经[测试](http://lib.csdn.net/base/softwaretest "软件测试知识库")使用soap1.1方式能调用soap1.1和soap1.2的服务端。

 

       缺点：

       唯一的缺点是，你得自己解析返回的XML，找到你关注的信息内容。