ITeye博客

httpclient妙用一 httpclient作为客户端调用webservice

thinkerAndThinker · 2017-07-17 19:56 · 开源框架 · 企业架构 · Markdown

1.个人观点

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

2.需求场景

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

[xml] view plain copy

 

 print?

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

     3.获取调用报文

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


     

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


     

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


        拿到的调用order的soap消息为:

 

[xml] view plain copy

 

 print?

  1. <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">
  2. <soapenv:Header/>
  3. <soapenv:Body>
  4. <web:order soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  5. <in0 xsi:type="web:OrderRequest">
  6. <mobile xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">?</mobile>
  7. <orderStatus xsi:type="xsd:int">?</orderStatus>
  8. <productCode xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">?</productCode>
  9. </in0>
  10. </web:order>
  11. </soapenv:Body>
  12. </soapenv:Envelope>

 

 

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

 

[xml] view plain copy

 

 print?

  1. <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">
  2. <soapenv:Header/>
  3. <soapenv:Body>
  4. <web:query soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  5. <in0 xsi:type="web:QueryRequest">
  6. <endTime xsi:type="xsd:dateTime">?</endTime>
  7. <mobile xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">?</mobile>
  8. <startTime xsi:type="xsd:dateTime">?</startTime>
  9. </in0>
  10. </web:query>
  11. </soapenv:Body>
  12. </soapenv:Envelope>

    

 

 4.用httpclient发送soap消息

   直接上代码,代码如下:

 

[java] view plain copy

 

 print?

  1. import java.nio.charset.Charset;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.client.config.RequestConfig;
  4. import org.apache.http.client.methods.CloseableHttpResponse;
  5. import org.apache.http.client.methods.HttpPost;
  6. import org.apache.http.entity.StringEntity;
  7. import org.apache.http.impl.client.CloseableHttpClient;
  8. import org.apache.http.impl.client.HttpClientBuilder;
  9. import org.apache.http.util.EntityUtils;
  10. import org.apache.log4j.Logger;
  11. public class HttpClientCallSoapUtil {
  12. static int socketTimeout = 30000;// 请求超时时间
  13. static int connectTimeout = 30000;// 传输超时时间
  14. static Logger logger = Logger.getLogger(HttpClientCallSoapUtil.class);
  15. /**
  16. * 使用SOAP1.1发送消息
  17. *
  18. * @param postUrl
  19. * @param soapXml
  20. * @param soapAction
  21. * @return
  22. */
  23. public static String doPostSoap1_1(String postUrl, String soapXml,
  24. String soapAction) {
  25. String retStr = "";
  26. // 创建HttpClientBuilder
  27. HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  28. // HttpClient
  29. CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
  30. HttpPost httpPost = new HttpPost(postUrl);
  31. //  设置请求和传输超时时间
  32. RequestConfig requestConfig = RequestConfig.custom()
  33. .setSocketTimeout(socketTimeout)
  34. .setConnectTimeout(connectTimeout).build();
  35. httpPost.setConfig(requestConfig);
  36. try {
  37. httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
  38. httpPost.setHeader("SOAPAction", soapAction);
  39. StringEntity data = new StringEntity(soapXml,
  40. Charset.forName("UTF-8"));
  41. httpPost.setEntity(data);
  42. CloseableHttpResponse response = closeableHttpClient
  43. .execute(httpPost);
  44. HttpEntity httpEntity = response.getEntity();
  45. if (httpEntity != null) {
  46. // 打印响应内容
  47. retStr = EntityUtils.toString(httpEntity, "UTF-8");
  48. logger.info("response:" + retStr);
  49. }
  50. // 释放资源
  51. closeableHttpClient.close();
  52. } catch (Exception e) {
  53. logger.error("exception in doPostSoap1_1", e);
  54. }
  55. return retStr;
  56. }
  57. /**
  58. * 使用SOAP1.2发送消息
  59. *
  60. * @param postUrl
  61. * @param soapXml
  62. * @param soapAction
  63. * @return
  64. */
  65. public static String doPostSoap1_2(String postUrl, String soapXml,
  66. String soapAction) {
  67. String retStr = "";
  68. // 创建HttpClientBuilder
  69. HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  70. // HttpClient
  71. CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
  72. HttpPost httpPost = new HttpPost(postUrl);
  73. // 设置请求和传输超时时间
  74. RequestConfig requestConfig = RequestConfig.custom()
  75. .setSocketTimeout(socketTimeout)
  76. .setConnectTimeout(connectTimeout).build();
  77. httpPost.setConfig(requestConfig);
  78. try {
  79. httpPost.setHeader("Content-Type",
  80. "application/soap+xml;charset=UTF-8");
  81. httpPost.setHeader("SOAPAction", soapAction);
  82. StringEntity data = new StringEntity(soapXml,
  83. Charset.forName("UTF-8"));
  84. httpPost.setEntity(data);
  85. CloseableHttpResponse response = closeableHttpClient
  86. .execute(httpPost);
  87. HttpEntity httpEntity = response.getEntity();
  88. if (httpEntity != null) {
  89. // 打印响应内容
  90. retStr = EntityUtils.toString(httpEntity, "UTF-8");
  91. logger.info("response:" + retStr);
  92. }
  93. // 释放资源
  94. closeableHttpClient.close();
  95. } catch (Exception e) {
  96. logger.error("exception in doPostSoap1_2", e);
  97. }
  98. return retStr;
  99. }
  100. public static void main(String[] args) {
  101. String orderSoapXml = "<?xml version = \"1.0\" ?>"
  102. + "<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\">"
  103. + "   <soapenv:Header/>"
  104. + "   <soapenv:Body>"
  105. + "      <web:order soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
  106. + "         <in0 xsi:type=\"web:OrderRequest\">"
  107. + "            <mobile xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">?</mobile>"
  108. + "            <orderStatus xsi:type=\"xsd:int\">?</orderStatus>"
  109. + "            <productCode xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">?</productCode>"
  110. + "         </in0>" + "      </web:order>"
  111. + "   </soapenv:Body>" + "</soapenv:Envelope>";
  112. String querySoapXml = "<?xml version = \"1.0\" ?>"
  113. + "<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\">"
  114. + "   <soapenv:Header/>"
  115. + "   <soapenv:Body>"
  116. + "      <web:query soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
  117. + "         <in0 xsi:type=\"web:QueryRequest\">"
  118. + "            <endTime xsi:type=\"xsd:dateTime\">?</endTime>"
  119. + "            <mobile xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">?</mobile>"
  120. + "            <startTime xsi:type=\"xsd:dateTime\">?</startTime>"
  121. + "         </in0>" + "      </web:query>"
  122. + "   </soapenv:Body>" + "</soapenv:Envelope>";
  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方式调用,经测试使用soap1.1方式能调用soap1.1和soap1.2的服务端。

 

       缺点:

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。