自学内容网 自学内容网

Java中实现发送xml参数的WebService接口调用

项目开发中与第三方系统数据对接遇到的问题,仅用作记录。

先将入参封装成Map,再将参数Map放入XML参数中,发送http请求(其中XML需要根据调用第三方系统提供修改),

@Test
    public void test1() {
        LinkedHashMap<String, Object> paramMap = new LinkedHashMap<>();
        paramMap.put("Factory", "001");
        paramMap.put("Process", "101");
        paramMap.put("Class", "A");

        StringBuffer params = new StringBuffer();
        params.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">\n" +
            "  <soapenv:Header/>\n" +
            "  <soapenv:Body>\n" +
            "     <tem:ApplyInfo>\n" );
        params.append( "    <tem:json>\n" + JSONUtil.toJsonStr(paramMap) +
            "    </tem:json>\n");
        params.append( "    </tem:ApplyInfo>\n" +
            "  </soapenv:Body>\n" +
            "</soapenv:Envelope>");
        // xml参数根据提供的接口进行修改

        try {
            // 发送请求代码
            URL url = new URL("xxxxxxxxxxxxx?wsdl");//xxxx替换为调用的接口地址
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.write(params.toString().getBytes("utf-8"));//params就是上面生成的xml内容
            dos.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            StringBuffer strBuf = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                strBuf.append(line);
            }
            dos.close();
            reader.close();
            String rs = strBuf.toString();
            System.out.println(rs);
            // 截取返回结果(根据返回的XML文件解析数据)
            String returnResult = rs.substring(rs.indexOf("{"),rs.indexOf("}")) + "}";
            JSONObject resJson = JSONUtil.parseObj(returnResult);
            System.out.println(resJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

获取结果后,根据需要从返回的XML中截取指定字符串转为对应的Json数据再分析。


原文地址:https://blog.csdn.net/csdnxyy/article/details/144219571

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!