基于HttpClient的WebService调用

作者: Men叔 | 来源:发表于2017-09-19 14:04 被阅读0次

    WebService的调用有很多种方式,本地调用(静态调用),远程调用(动态)

    关于上边静态,动态是我个人的理解,没有权威性,个人喜好而已

    本地调用

    具体操作请看:http://www.jianshu.com/p/1e9582a4b340

    远程调用

    远程调用的方式比较多,例如利用cxf,axis、axis2 、HttpClient等框架的调用,这里具体看基于HttpClient的调用, HttpClient 3和4 使用方式稍有区别,经测试,4.5.2版本不支持jdk1.5

    • HttpClient 3.x
    public static String doPostSOAP_RemoveUser(String logonName){
            Properties prop = new Properties(); 
            PostMethod post = null;
            String responseXml = null;
            String json= null;
            try {
            InputStream in = HttpClient3_0_SOAPUtil.class.getResourceAsStream("/sysPath.properties");
            prop.load(in);
            String postURL = prop.getProperty("postURL");
            post = new PostMethod(postURL);
            post.setRequestHeader("Content-Type","text/xml;charset=utf-8");
                //File input = new File(strXMLFilename);
                // Prepare HTTP post
                // Request content will be retrieved directly
                // from the input stream
                    String systemId = prop.getProperty("systemId");                      
                    String strWSDLXml_RemoveUser = "<?xml version = \"1.0\" ?>" 
                            + "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\">"
                            + "   <soap:Header/>"
                            + "   <soap:Body>"
                            + "      <tem:RemoveUser>"
                            + "         <!--Optional:-->"
                            + "         <tem:systemId>"+systemId+"</tem:systemId>"
                            + "         <!--Optional:-->"
                            + "         <tem:logonName>"+logonName+"</tem:logonName>"
                            + "      </tem:RemoveUser>"
                            + "   </soap:Body>"
                            + "</soap:Envelope>";
                    System.out.println(strWSDLXml_RemoveUser);
                    String strSoapAction_RemoveUser = prop.getProperty("strSoapAction_RemoveUser");
                byte[] b = strWSDLXml_RemoveUser.getBytes("utf-8");
                InputStream is = new ByteArrayInputStream(b,0,b.length);
                RequestEntity entity = new InputStreamRequestEntity(is,b.length,"application/soap+xml; charset=utf-8");
                post.setRequestEntity(entity);
                // consult documentation for your web service
                post.setRequestHeader("SOAPAction", strSoapAction_RemoveUser);
                // Get HTTP client
                HttpClient httpclient = new HttpClient();
                // Execute request
                int result = httpclient.executeMethod(post);
                // Display status code
                //System.out.println("Response status code: " + result);
                // Display response
                //System.out.println("Response body: ");
                responseXml = post.getResponseBodyAsString();
                //System.out.println(responseXml);
                Document document_ret = DocumentHelper.parseText(responseXml);
                json = document_ret.getRootElement().element("Body").element("RemoveUserResponse").element("RemoveUserResult").getText();
                
            }catch (Exception e) {
                e.printStackTrace();
            } finally {
                // Release current connection to the connection pool once you are done
                post.releaseConnection();
            }
            return json;
        }
    

    这是我个人根据相应业务而产生的代码,不同业务可根据业务需求做相应的改动,strWSDLXml_RemoveUser 这个字符串是在soapUI 中得到,

    image.png

    关于soapUI我也是小白,不多做解释,具体自行百度、google。
    上述代码使用了到了外部配置文件


    sysPath 内容如下

    systemId=xxxxxxxxxxxxxxxxxxxx
    postURL=http://xxx.xxx.xxx.xxx:9999/webservice/externalservice/userservice.asmx
    strSoapAction_RemoveUser=http://xxxxxx.xxx/RemoveUse
    

    jar 包依赖关系

    image.png

    调用上述方法,将会得到调用webService后的响应内容
    下边给出3.x的官方提供的示例

    import java.io.File;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.methods.FileRequestEntity;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.methods.RequestEntity;
    
    /**
     *
     * This is a sample application that demonstrates
     * how to use the Jakarta HttpClient API.
     *
     * This application sends an XML document
     * to a remote web server using HTTP POST
     *
     * @author Sean C. Sullivan
     * @author Ortwin Glueck
     * @author Oleg Kalnichevski
     * @author Paul King
     */
    public class PostSOAP {
    
        /**
         *
         * Usage:
         *          java PostSOAP http://mywebserver:80/ SOAPAction c:\foo.xml
         *
         *  @param args command line arguments
         *                 Argument 0 is a URL to a web server
         *                 Argument 1 is the SOAP Action
         *                 Argument 2 is a local filename
         *
         */
        public static void main(String[] args) throws Exception {
            if (args.length != 3) {
                System.out.println("Usage: java -classpath <classpath> [-Dorg.apache.commons.logging.simplelog.defaultlog=<loglevel>] PostSOAP <url> <soapaction> <filename>]");
                System.out.println("<classpath> - must contain the commons-httpclient.jar and commons-logging.jar");
                System.out.println("<loglevel> - one of error, warn, info, debug, trace");
                System.out.println("<url> - the URL to post the file to");
                System.out.println("<soapaction> - the SOAP action header value");
                System.out.println("<filename> - file to post to the URL");
                System.out.println();
                System.exit(1);
            }
            // Get target URL
            String strURL = args[0];
            // Get SOAP action
            String strSoapAction = args[1];
            // Get file to be posted
            String strXMLFilename = args[2];
            File input = new File(strXMLFilename);
            // Prepare HTTP post
            PostMethod post = new PostMethod(strURL);
            // Request content will be retrieved directly
            // from the input stream
            RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
            post.setRequestEntity(entity);
            // consult documentation for your web service
            post.setRequestHeader("SOAPAction", strSoapAction);
            // Get HTTP client
            HttpClient httpclient = new HttpClient();
            // Execute request
            try {
                int result = httpclient.executeMethod(post);
                // Display status code
                System.out.println("Response status code: " + result);
                // Display response
                System.out.println("Response body: ");
                System.out.println(post.getResponseBodyAsString());
            } finally {
                // Release current connection to the connection pool once you are done
                post.releaseConnection();
            }
        }
    }
    

    3.x 项目官方地址:http://hc.apache.org/httpclient-3.x/

    jar包依赖


    image.png
     public static String doPostSoap1_1(String postUrl, String soapXml,  
                    String soapAction) {  
                String retStr = "";  
              
                // 创建HttpClientBuilder  
                HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
                // HttpClient  
                CloseableHttpClient closeableHttpClient = httpClientBuilder.build();  
                HttpPost httpPost = new HttpPost(postUrl);  
                        //  设置请求和传输超时时间  
                RequestConfig requestConfig = RequestConfig.custom()  
                        .setSocketTimeout(socketTimeout)  
                        .setConnectTimeout(connectTimeout).build();  
                httpPost.setConfig(requestConfig);  
                try { 
                    httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");  
                    httpPost.setHeader("SOAPAction", soapAction);  
                    StringEntity data = new StringEntity(soapXml,  
                            Charset.forName("UTF-8"));  
                    httpPost.setEntity(data);  
                    CloseableHttpResponse response = closeableHttpClient.execute(httpPost);  
                    HttpEntity httpEntity = response.getEntity();  
                    if (httpEntity != null) {  
                        // 打印响应内容  
                        retStr = EntityUtils.toString(httpEntity, "UTF-8");  
                       System.out.println("response:" + retStr);  
                    }  
                    // 释放资源  
                    closeableHttpClient.close();  
                } catch (Exception e) {  
                   // logger.error("exception in doPostSoap1_1", e);  
                    e.printStackTrace();
                }  
                return retStr;  
            }  
         public static void main(String[] args) {
                    String systemId = "ssss";
                    String jsonUserInfo="";
                    String adduser = "<?xml version = \"1.0\" ?>" 
                            + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">"
                            + "   <soapenv:Header/>"
                            + "   <soapenv:Body>"
                            + "      <tem:AddUser>"
                            + "         <!--Optional:-->"
                            + "         <tem:systemId>"+systemId+"</tem:systemId>"
                            + "         <!--Optional:-->"
                            + "         <tem:jsonUserInfo>"+jsonUserInfo+"</tem:jsonUserInfo>"
                            + "      </tem:AddUser>"
                            + "   </soapenv:Body>"
                            + "</soapenv:Envelope>";
                    String postUrl = "http://1xxx.xxx.x.x:9999/webservice/externalservice/userservice.asmx"; 
                    String repXml= doPostSoap1_1(postUrl, adduser, "http://tempuri.org/AddUser");                          
            }
    

    之后解析repXml得到响应的json 字符串;

    相关文章

      网友评论

        本文标题:基于HttpClient的WebService调用

        本文链接:https://www.haomeiwen.com/subject/sogdjxtx.html