Java - XML Parser & Downloader


Sto creando un'applicazione che scaricherà molti file dal mio server web. Ma idk perché non funziona. Non ha alcuna risposta..

Ecco una parte del mio codice

Downloader.classe

private Proxy proxy = Proxy.NO_PROXY;
    public void downloadLibrary()
        {
            System.out.println("Start downloading libraries from server...");
            try
            {
                URL resourceUrl = new URL("http://www.example.com/libraries.xml");
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(resourceUrl.openConnection(proxy).getInputStream());
                NodeList nodeLst = doc.getElementsByTagName("Contents");
                for (int i = 0; i < nodeLst.getLength(); i++)
                {
                    Node node = nodeLst.item(i);

                    if (node.getNodeType() == 1)
                    {
                        Element element = (Element)node;
                        String key = element.getElementsByTagName("Key").item(0).getChildNodes().item(0).getNodeValue();
                        File f = new File(launcher.getWorkingDirectory(), key);
                        downloadFile("http://www.example.com/" + key, f, "libraries");
                    }
                }
            }
            catch(Exception e)
            {
                System.out.println("Error was found when trying to download libraries file " + e);
            }

        }

        public void downloadFile(final String url, final File path, final String fileName)
        {
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>()
            {
                @Override
                protected Void doInBackground() throws Exception
                {
                    launcher.println("Downloading file " + fileName + "...");
                    try
                    {
                        URL fileURL = new URL(url);
                        ReadableByteChannel rbc = Channels.newChannel(fileURL.openStream());
                        FileOutputStream fos = new FileOutputStream(path);
                        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                    }
                    catch(Exception e)
                    {
                        System.out.println("Cannot download file : " + fileName + " " + e);
                    }
                    return null;
                }
                @Override
                public void done()
                {
                    System.out.println(fileName + " had downloaded sucessfully");

                }
            };
            worker.execute();
        }

Ecco una parte del mio file xml(librerie.xml)

<Key>libraries/org/lwjgl/lwjgl/lwjgl/2.9.0/lwjgl-2.9.0.jar</Key>

La mia idea è che la mia applicazione leggerà il file XML. Quindi scaricherà il file dal server e salverà sul computer. Ad esempio, la mia applicazione scarica {[2] } quindi salverà in C://WorkingDir/libraries/org/lwjgl/lwjgl/lwjgl/2.9.0/lwjgl-2.9.0.jar C' è una tonnellata di <Key></Key> nel mio file XML e devo scaricarlo tutto.

C'è qualche codice sbagliato? Grazie per l'aiuto.

Author: Jeremy, 2013-10-01

1 answers

Prova prima a consumare la connessione direttamente attraverso un lettore di qualche tipo a una stringa, quindi puoi manipolarla comunque ti serve.

package come.somecompany.somepackage.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class WebUtils {

    /**
     * Gets the HTML value of a website and
     * returns as a string value.
     * 
     * @param website website url to get.
     * @param ssl True if website is SSL.
     * @param useragent Specified User-Agent (empty string "" means use system default).
     * @return String value of website.
     */
    public String getHTML(String website, boolean ssl, String useragent) {
        String html = "";
        String temp;
        String prefix;
        if (ssl) {
            prefix = "https://";
        } else {
            prefix = "http://";
        }
        try {
            URL url = new URL(prefix + website);
            URLConnection con = url.openConnection();
        if (!(useragent.equalsIgnoreCase(""))) {
            con.setRequestProperty("User-Agent", useragent);
        }
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        while((temp = in.readLine()) != null) {
            html += temp + "\n";
        }
        in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return html;
    }
}

Inoltre, sembra che tu stia tentando di analizzare HTML usando un pattern XML... che può dare difficoltà. Potresti provare JSoup - è un parser HTML java, funziona abbastanza bene ed è facile: http://jsoup.org /

Può aiutare con il consumo di documenti dal tuo sito web senza bisogno di costruire il proprio downloader troppo.

UPDATE --

Prova a leggere in un BufferedReader, forse il tuo programma non sta ricevendo il documento completo, buffered reader potrebbe essere d'aiuto.

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

Quindi con il tuo primo metodo, qualcosa come:

public void downloadLibrary()
    {
        System.out.println("Start downloading libraries from server...");
        try
        {
            URL resourceUrl = new URL("http://www.example.com/libraries.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            // change here
            URLConnection con = resourceUrl.openConnection();
            BufferedReader bfr = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String tempDoc = "";
            String tempStr;
            while (tempStr = bfr.readLine()) != null) {
                tempDoc += tempStr + System.getProperty("line.separator");
            }

            Document doc = db.parse(tempDoc);

            NodeList nodeLst = doc.getElementsByTagName("Contents");
            for (int i = 0; i < nodeLst.getLength(); i++)
            {
                Node node = nodeLst.item(i);

                if (node.getNodeType() == 1)
                {
                    Element element = (Element)node;
                    String key = element.getElementsByTagName("Key").item(0).getChildNodes().item(0).getNodeValue();
                    File f = new File(launcher.getWorkingDirectory(), key);
                    downloadFile("http://www.example.com/" + key, f, "libraries");
                }
            }
        }
        catch(Exception e)
        {
            System.out.println("Error was found when trying to download libraries file " + e);
        }

    }
 1
Author: SnakeDoc, 2013-10-01 15:30:36