`
thinkerAndThinker
  • 浏览: 276621 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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

阅读更多

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

 

 5.总结

       优点:

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

       2.使用httpclient调用webservice,建议采用soap1.1方式调用,经测试使用soap1.1方式能调用soap1.1和soap1.2的服务端。

 

       缺点:

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics