springboot 调用WebService功能优化

  1. 正常调用一个webservice,你的功能是酱紫滴
import okhttp3.*;
import java.io.IOException;

public class SoapRequestExample {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient.Builder().build();

        String url = "https://ip/接口名";
        String contentType = "application/xml";
        String soapAction = "";

        // SOAP请求体
        String soapRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
                "<soapenv:Envelope \r\n" +
                "    xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n" +
                "    xmlns:hrx=\"http://ip/\">\r\n" +
                "    <soapenv:Header/>\r\n" +
                "    <soapenv:Body>\r\n" +
                "    <hrx:excute>\r\n" +
                "            <sourceData>\r\n" +
                "                <all></all>\r\n" +
                "                <page>1</page>\r\n" +
                "                <pageSize>1</pageSize>\r\n" +
                "            </sourceData>\r\n" +
                "        </hrx:excute>\r\n" +
                "    </soapenv:Body>\r\n" +
                "</soapenv:Envelope>";

        MediaType mediaType = MediaType.parse(contentType);
        RequestBody body = RequestBody.create(mediaType, soapRequest);

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                // 处理成功响应
                String responseBody = response.body().string();
                System.out.println("Response:\n" + responseBody);
            } else {
                // 处理失败响应
                System.out.println("Request failed with code: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.功能实现了,但是soapRequest参数都代码里,看起来很丑陋
所以需要优化一下.

2.1创建一个FreeMarker模板文件,例如soap-request-template.ftl

<#assign soapenv = 'http://schemas.xmlsoap.org/soap/envelope/'>
<#assign hrx = 'http://webservice.co.hrx.zjenergy.com.cn/'>

<#-- 定义SOAP请求 -->
<soapenv:Envelope xmlns:soapenv="${soapenv}" xmlns:hrx="${hrx}">
    <soapenv:Header/>
    <soapenv:Body>
        <hrx:excute>
            <sourceData>
                <all>${allValue}</all>
                <page>${pageValue}</page>
                <pageSize>${pageSizeValue}</pageSize>
            </sourceData>
        </hrx:excute>
    </soapenv:Body>
</soapenv:Envelope>

2.2 使用FreeMarker来加载和渲染模板

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class SoapTemplateGenerator {

    public static void main(String[] args) throws IOException, TemplateException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
        configuration.setClassForTemplateLoading(SoapTemplateGenerator.class, "/templates");
        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        // 创建数据模型,将参数传递给模板
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("allValue", "");
        dataModel.put("pageValue", 1);
        dataModel.put("pageSizeValue", 1);

        Template template = configuration.getTemplate("soap-request-template.ftl");

        // 渲染模板
        StringWriter stringWriter = new StringWriter();
        template.process(dataModel, stringWriter);

        String soapRequestBody = stringWriter.toString();
        System.out.println(soapRequestBody);
    }
}
  1. 接着把模板数据当参数,进行调用
 public void syncHrxCompanyInfo() {
        try {
            Response response = getHrxCompanyInfo("hrx_company_info.ftl",companyInfoUrl);
            assert response.body() != null;
            String respData = response.body().string();

            try {
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(new InputSource(new StringReader(respData)));
                doc.getDocumentElement().normalize();

                NodeList dataList = doc.getElementsByTagName("data");
                if (dataList.getLength() > 0) {
                    Node dataNode = dataList.item(0);
                    // 把data数组的数据,存到数组里
                    String data = dataNode.getTextContent();
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode jsonNode = objectMapper.readTree(data);
                    System.out.println("ListSize: " + jsonNode.size());
                    List<Record> companyInfoRecordList = new ArrayList<>();
                    for (JsonNode objectNode : jsonNode) {
                        JsonNode parentFullId = objectNode.get("pId");
                        String parentStructFullId =null;
                        if (Objects.nonNull(parentFullId)){
                             parentStructFullId = parentFullId.asText();
                        }
                        String shortName = objectNode.get("name").asText();
                        String structFullId = objectNode.get("id").asText();
                        Record record = new Record();
                        if (StrUtil.isNotBlank(parentStructFullId)){
                            record.setParentStructFullId(parentStructFullId);
                        }
                        record.setShortName(shortName);
                        record.setStructFullId(structFullId);
                        companyInfoRecordList.add(record);
                    }
                    if (CollUtil.isNotEmpty(companyInfoRecordList)){
                        // 删除原来数据
                        hrxCompanyInfoDao.deleteAll();
                        // 分批插入 每1000一组
                        List<List<Record>> parts = Lists.partition(companyInfoRecordList, 1000);
                        parts.forEach(list -> {
                            hrxCompanyInfoDao.batchInsert(companyInfoRecordList);
                        });
                    }
                }
            } catch (Exception e) {
                log.error("保存公司信息异常", e);
            }
        } catch (Exception e) {
            log.error("保存公司信息失败", e);
        }
    }

    public Response getHrxCompanyInfo(String templateName,String requestUrl) throws NoSuchAlgorithmException, KeyManagementException, IOException, TemplateException {
        // 跳过ssl验证,因为人家没有
        OkHttpClient client = new OkHttpClient().newBuilder()
                .sslSocketFactory(OkHttpUtil.getIgnoreInitedSslContext().getSocketFactory(), OkHttpUtil.IGNORE_SSL_TRUST_MANAGER_X509)
                .hostnameVerifier(OkHttpUtil.getIgnoreSslHostnameVerifier())
                .build();

        MediaType mediaType = MediaType.parse(HrxTemplateConstants.contentType);
        // 把请求体里xml参数,转成ftl模板,改为动态参到模板,然后读取模板信息
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
        // 读取路径
        configuration.setClassForTemplateLoading(HrxCompanyInfoService.class, "/templates/email");
        configuration.setDefaultEncoding(HrxTemplateConstants.encoding);
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        // 创建数据模型,将参数传递给模板
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("allValue", "");
        // 模板名称
        Template template = configuration.getTemplate(templateName);
        // 渲染模板
        StringWriter stringWriter = new StringWriter();
        template.process(dataModel, stringWriter);
        String soapRequestBody = stringWriter.toString();
        System.out.println(soapRequestBody);
//            RequestBody body = RequestBody.create(mediaType, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<soapenv:Envelope \r\n    xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n    xmlns:hrx=\"http://webservice.co.hrx.zjenergy.com.cn/\">\r\n    <soapenv:Header/>\r\n    <soapenv:Body>\r\n    <hrx:excute>\r\n            <sourceData>\r\n                <all></all>\r\n                <page>1</page>\r\n                <pageSize>1</pageSize>\r\n            </sourceData>\r\n        </hrx:excute>\r\n    </soapenv:Body>\r\n</soapenv:Envelope>");
        RequestBody body = RequestBody.create(mediaType, soapRequestBody);
        // 构造请求
        Request request = new Request.Builder()
                .url(requestUrl)
                .post(body)
                .addHeader("Content-Type", HrxTemplateConstants.mediaType)
                .addHeader("SOAPAction", "")
                .addHeader("content-type", HrxTemplateConstants.contentType)
                .build();

        return client.newCall(request).execute();
    }
public class HrxTemplateConstants {

    public static final String contentType = "application/xml";

    public static final String mediaType = "text/xml";

    public static final String encoding = "UTF-8";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值