Saxparser exception on Android

I am parsing data from this XML url . Text input is user dependent. Whenever there are spaces in a text variable, I get this exception:

org.apache.harmony.xml.ExpatParser$ParseException: At line 11, column 2: mismatched tag org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:520) org.apache.harmony.xml.ExpatParser.parseDocument(ExpatParser.java:479) org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:318) org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:275) gps.app.tkartor.XMLObjects.XMLParser.findStreet(XMLParser.java:99) 

If there are no spaces, it works fine. Code parsing:

 public void findStreet(String searchWord) { try { url = new URL( "http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/TextSearch?text=" + searchWord + "&maxResults=100"); System.out.println(url.toString()); parserFactory = SAXParserFactory.newInstance(); parser = parserFactory.newSAXParser(); reader = parser.getXMLReader(); streetHandler = new StreetHandler(); reader.setContentHandler(streetHandler); reader.parse(new InputSource(url.openStream()));//line 99 poi = streetHandler.getAllStreets(); } catch (Exception e) { e.printStackTrace(); } } 
+4
source share
2 answers

Specify spaces with '+'

http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/TextSearch?text=West+bar&maxResults=100

So, in your case, you need to replace the spaces of your searchWord string. Sort of

  searchWord = searchWord.replace(" ", "+"); 
+1
source

When I browse both of these URLs using my web browser, I get valid XML. Of course, in line 11 there is no error indicated by your glass.

My conclusion is that choosing URLs (in particular, with space in it) gives a different result when you do this programmatically rather than executing it in a web browser. I expect this because the browser β€œhelps” to correct the URL to encode the space character before sending it. (And I suspect you have inserted this fixed URL into the question ...)

To confirm this diagnosis, you need to capture and view the actual contents of the file that your Android application receives from the server. I assume this is actually an HTML error page. Usually this will not be valid XML and therefore an XML parsing error.

If this turns out to be a problem, you need to correctly encode the search string before embedding it in the url. If you used plain Java, I would suggest using URLEncoder.encode or URLEncoder.encode URL from your components using the URI class. On Android platform, there may be a better way ...

+1
source

Source: https://habr.com/ru/post/1403290/


All Articles