java 发送xml数据,并将接收到的xml转数组

发送xml

public static void testInterface(String reqPath, String reqXml){
        try{

            Encoder encoder = Base64.getEncoder();

            URL reqURL = new URL(reqPath);
            HttpURLConnection conn   = (HttpURLConnection) reqURL.openConnection();
            conn.setRequestMethod("POST");
            //设置发送数据
            conn.setDoOutput(true);
            conn.setRequestProperty("Accept", "text/plain");
            System.out.println("请求报文:[" + reqXml + "]");
            reqXml = reqXml.replaceAll("\\r", "").replaceAll("\\n", "");
            reqXml = encoder.encodeToString(reqXml.getBytes());

            byte[] bytes = reqXml.getBytes("UTF-8");
            conn.getOutputStream().write(bytes);

            InputStream resInput = conn.getInputStream();
            //定义字节数组
            byte[] b = new byte[1024];

            //定义一个输出流存储接收到的数据
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            //开始接收数据
            int len = 0;
            while (true) {
                len = resInput.read(b);
                if (len == -1) {
                    //数据读完
                    break;
                }
                byteArrayOutputStream.write(b, 0, len);
            }
            //从输出流中获取读取到数据(服务端返回的)
            String response = byteArrayOutputStream.toString();

            Decoder decoder = Base64.getDecoder();
            System.out.println("返回报文"+ new String(decoder.decode(response)));
            System.out.println(org.json.XML.toJSONObject(new String(decoder.decode(response))).toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

传入的数据大概是这样的

public static String getXmlInfo() {
        StringBuilder sb = new StringBuilder();
        sb.append("");
        sb.append("    
"); sb.append(" 1"); sb.append(" service"); sb.append("
"); sb.append(" "); sb.append(" 0000021000011001"); sb.append(" 33647405"); sb.append(" mnt/5.0.217.50/resources/80009.mov"); sb.append(" 0000021000011001"); sb.append(" "); sb.append("
"); return sb.toString(); }

解析xml
pom文件


    org.json
    json
    20180130

然后解析

System.out.println(org.json.XML.toJSONObject(new String(decoder.decode(response))).toString());

你可能感兴趣的:(java 发送xml数据,并将接收到的xml转数组)