Java 通过Soap方式调用WebService接口

时间:2025-02-16 08:33:19
import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class WebServiceTest {
    public static void main(String[] args) {
        String url = "http://192.168.42.111:8080/web/services/testServImpl?wsdl";
        // 根据实际情况拼接xml
        String xmlData = "<soapenv:Envelope\n" +
                "    xmlns:soapenv=\"/soap/envelope/\"\n" +
                "    xmlns:impl=\"\">\n" +
                "    <soapenv:Header></soapenv:Header>\n" +
                "    <soapenv:Body></soapenv:Body>\n" +
                "</soapenv:Envelope>";

        String postSoap = doPostSoap(url, xmlData, "");
        // 去除转义字符
        String unPostSoap = (postSoap);
        (unPostSoap);
    }

    //使用SOAP1.1发送消息
    public static String doPostSoap(String postUrl, String soapXml, String soapAction) {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = ();
        // HttpClient
        CloseableHttpClient closeableHttpClient = ();
        HttpPost httpPost = new HttpPost(postUrl);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = ().setSocketTimeout(6000)
                .setConnectTimeout(6000).build();
        (requestConfig);
        try {
            ("Content-Type", "text/xml;charset=UTF-8");
            ("SOAPAction", soapAction);
            StringEntity data = new StringEntity(soapXml, ("UTF-8"));
            (data);
            CloseableHttpResponse response = (httpPost);
            HttpEntity httpEntity = ();
            if (httpEntity != null) {
                // 打印响应内容
                retStr = (httpEntity, "UTF-8");
                ("response:" + retStr);
            }
            // 释放资源
            ();
        } catch (Exception e) {
            ();
        }
        return retStr;
    }

}