JAvaはxmlデータを送信し、受信したxmlを配列に変換する

3044 ワード

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("\
", ""); 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());