java HttpClient 访问webservice并解析返回数据

关于webservice的普及就不多说了,直接进入主题吧。

1.导包

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient HttpClient相关包-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/jaxen/jaxen Xpath解析包-->
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>

2.访问webservice

2.1访问

/**
     * 发起webservice请求
     * @param url
     * @param soap
     * @param SOAPAction
     * @return
     */
    public static String doPostSoap(String url, String soap, String SOAPAction) {
        //请求体
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(url);
        //  设置请求和传输超时时间
        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(soap,
                    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.err.println("response:" + retStr);
            }
            // 释放资源
            closeableHttpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retStr;
    }

2.2 测试

public static void main(String[] args){
        String url = "http://192.168.1.3:58080";
        //请求体
        String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:pm=\"http://www.getpostman.com/\">" +
                "<soapenv:Header></soapenv:Header>" +
                "    <soapenv:Body>" +
                "        <getTransRecordTop5 xmlns=\"urn:BankYktWebSrv\">" +
                "            <cardid>12273</cardid>" +
                "        </getTransRecordTop5>" +
                "    </soapenv:Body>" +
                "</soapenv:Envelope>";
        String res = doPostSoap(url,soap,"");
        System.out.println(res);
    }

 返回数据:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="http://192.168.1.3:58080/BankYktWebSrv.wsdl" xmlns:ns2="urn:BankYktWebSrv"><SOAP-ENV:Header></SOAP-ENV:Header>
<SOAP-ENV:Body>
    <ns2:getTransRecordTop5Response>
        <result>
            { "code":0, "message":"success", "data":[ { "card_id":"12273", "amount":"10.00", "trans_time":"2018-11-20 14:07:28", "status":"1" },{ "card_id":"12273", "amount":"10.00", "trans_time":"2018-11-19 14:55:54", "status":"0" },{ "card_id":"12273", "amount":"10.00", "trans_time":"2018-11-17 23:25:50", "status":"0" },{ "card_id":"12273", "amount":".01", "trans_time":"2018-11-17 16:19:03", "status":"0" },{ "card_id":"12273", "amount":".01", "trans_time":"2018-11-16 20:49:02", "status":"0" } ] }
        </result>
    </ns2:getTransRecordTop5Response>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

3.解析webservice返回信息

3.1解析

/**
     * 解析webservice的返回结果
     * @param str xml内容
     * @param nodeName 需要获取的正文内容节点名
     * @return
     */
    public static String getWebservicesBody(String str,String nodeName){
        String s = "";
        try {
            Document doc = DocumentHelper.parseText(str);
            DefaultXPath xpath = new DefaultXPath("//"+nodeName);
           //下面的wsdl文件地址需要自己更改,返回数据中一般都有 
xpath.setNamespaceURIs(Collections.singletonMap("ns1","http://192.168.1.3:58080/BankYktWebSrv.wsdl"));

            List list = xpath.selectNodes(doc);
            Iterator iterator = list.iterator();
            while (iterator.hasNext()) {
                Element node = (Element) iterator.next();
                s = node.getText();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        System.err.println("Webservices result:"+s);
        return s;
    }

3.2测试

个人习惯转json

public static void main(String[] args){
        String url = "http://192.168.1.3:58080";
        //请求体
        String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:pm=\"http://www.getpostman.com/\">" +
                "<soapenv:Header></soapenv:Header>" +
                "    <soapenv:Body>" +
                "        <getTransRecordTop5 xmlns=\"urn:BankYktWebSrv\">" +
                "            <cardid>12273</cardid>" +
                "        </getTransRecordTop5>" +
                "    </soapenv:Body>" +
                "</soapenv:Envelope>";
        String res = doPostSoap(url,soap,"");
        String formatStr = getWebservicesBody(res,"result");
        //System.out.println(formatStr);
        JSONObject json = JSONObject.parseObject(formatStr);
        System.out.println(json);
    }

测试结果图

error输出的是获取result节点的数据。

下面是转json格式的数据。

json我用的是阿里巴巴那个:com.alibaba.fastjson.JSONObject

猜你喜欢

转载自blog.csdn.net/u012667477/article/details/84305411
今日推荐