繁体   English   中英

如何从Java中获取URL的xml响应并将其存储在MONGODB中

[英]How to get xml response from URL in Java and store It in MONGODB

我想请求一个URL,它将返回如下的xml响应:

<SERVERPERFORMANCEMETRICS>
<SERVERNAME>abc</SERVERNAME> 
<SERVERSTARTUPTIME>11/25/2016 11:00 AM</SERVERSTARTUPTIME> 
<TOTALMASTERREQUESTS>4</TOTALMASTERREQUESTS> 
<TOTALRENDERERREQUESTS>13</TOTALRENDERERREQUESTS> 
<FAILEDREQUESTS>10</FAILEDREQUESTS>
</SERVERPERFORMANCEMETRICS>

现在我想在MONGODB中解析并存储这个xml的数据。

        URL url;
        HttpURLConnection urlConnection = null; 


        MongoClientURI mongoClientURI = new MongoClientURI(dbURL);
        MongoClient mongoClient = new MongoClient(mongoClientURI);

        /*  To connect database, you need to specify the database name, if the database 
            doesn't exist then MongoDB creates it automatically. */
        MongoDatabase mongoDatabase = mongoClient.getDatabase("myDb");
        System.out.println("Connected to database successfully");

        MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("myCollection");
        System.out.println("Collection created successfully");

        url = new URL(targetURL);
        urlConnection =  (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        InputStreamReader inputStreamReader =  new InputStreamReader(inputStream);

使用W3C的DocumentBuilder

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(inputStream);

我自己使用json-java jar找到了解决方案

       if (inputStream != null) {
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            //BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = bufferedReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }

            JSONObject jsonObject = XML.toJSONObject(responseStrBuilder.toString());
            System.out.println(jsonObject);

            org.bson.Document jsonDocument = org.bson.Document.parse(jsonObject.toString());
            mongoCollection.insertOne(jsonDocument);
            System.out.println("Collection inserted successfully");
        }   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM