steven_h
steven_h

Reputation: 93

How to make the SAX Parser wait for a file to finish downloading before it is parsed?

I am having a problem where my XML files are slow to load and don't finish downloading before they start to be parsed which throws an xml not well formatted exception from my parser showing that the file downloaded incompletely.

The complete error from logcat is "ERROR/Error(323): errororg.apache.harmony.xml.ExpatParser$ParseException: At line 10, column 46: not well-formed (invalid token)"

I know the xml file is correct because sometimes it will work and I can also pull it up in my browser and look at it.

What would be the best way to make the parser wait for the InputSource before continuing on and parsing the xml data?

The code below is the code I use to get the file and parse it.

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
GradeHandler gradeHandler = new GradeHandler();
xr.setContentHandler(gradeHandler);
URL url = new URL("https://url/to/xml/file");
HttpsURLConnection ucon = (HttpsURLConnection)url.openConnection();
ucon.setHostnameVerifier(new AllowAllHostnameVerifier());
xr.parse(new InputSource(new BufferedInputStream(ucon.getInputStream())));

Upvotes: 0

Views: 985

Answers (1)

Kevin
Kevin

Reputation: 30449

What would be the best way to make the parser wait for the InputSource before continuing on and parsing the xml data?

Perhaps by downloading the response first before using it?

ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(ucon.getInputStream(), output);
xr.parse(new InputSource(new ByteArrayInputStream(output.toByteArray());

Upvotes: 3

Related Questions