简体   繁体   English

如何在Android上从远程服务器获取XML文件

[英]How to write XML file on Android, getting from remote server

I need sometimes read XML file from remote server, and replace data in XML on my Android device. 有时我需要从远程服务器读取XML文件,并替换Android设备上XML中的数据。 I read data through XmlPullParser: 我通过XmlPullParser读取数据:

XmlPullParser users;
            try {
                URL xmlUrl = new URL("http://xx.xx.xx.xx/1.xml");
                users = XmlPullParserFactory.newInstance().newPullParser();
                users.setInput(xmlUrl.openStream(), null);

            }

How can I replace it on Android? 如何在Android上替换它?

Simply use this code, it's overwrites the file with the new file you download from the internet. 只需使用此代码,它就会用您从Internet下载的新文件覆盖文件。

public static boolean downloadFile(String fileToDownload, File newPath,
            String newFileName) {
        try {
            URL url = new URL(fileToDownload);
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.connect();
            if (!newPath.isDirectory()) {

                CreateLog.createFolder(newPath.toString());
            }
            File file = new File(newPath.toString() + "/" + newFileName);
            if (!file.isFile()) {
                CreateLog.writeLogToFile(newPath.toString() + newFileName,
                        "%TEMP%");
            }

            FileOutputStream fileOutput = new FileOutputStream(file);
            InputStream inputStream = urlConnection.getInputStream();

            byte[] buffer = new byte[1024];
            int bufferLength = 0;

            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer, 0, bufferLength);
            }
            fileOutput.close();
            return true;

        } catch (MalformedURLException e) {
            CreateLog.addToLog(e.toString());
            return false;
        } catch (IOException e) {
            CreateLog.addToLog(e.toString());
            return false;
        }
    }

public static void createFolder(String filePath) {
    File createFolder = new File(filePath);
    createFolder.mkdirs();
}

A cleaner method is to use a Asynctask , the code runs in a new thread. 一种更干净的方法是使用Asynctask ,代码在新线程中运行。 But it's a bit harder to code. 但这很难编码。

private class GetProblems extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            for (String myUrl : params) {

                try {

                    URL url = new URL(myUrl);
                    URLConnection ucon = url.openConnection();
                    ucon.setRequestProperty("Accept", "application/xml");

                    InputStream is = ucon.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);

                    ByteArrayBuffer baf = new ByteArrayBuffer(50);
                    int current = 0;
                    while ((current = bis.read()) != -1) {
                        baf.append((byte) current);
                    }
                    String str = new String(baf.toByteArray(), "UTF8");

                    return str;

                } catch (MalformedURLException e) {
                    CreateLog.addToLog("[GetProblems] " + e.toString());
                } catch (IOException e) {
                    CreateLog.addToLog("[GetProblems] " + e.toString());
                }
            }
            return "error";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            // updateProgressBar(values[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

                        ...write result to a file

        }
    }

Run the AsyncTask code: 运行AsyncTask代码:

new GetProblems().execute("http://myurl.com/xmlfile.xml");

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

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