the following code is for xml parsing.
try
{
HttpEntity entity = response.getEntity();
final InputStream in = entity.getContent();
final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
final XmlHandler handler = new XmlHandler();
Reader reader = new InputStreamReader(in, "UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
parser.parse(is, handler);
//TODO: get the data from your handler
}
catch (final Exception e)
{
Log.e("ParseError", "Error parsing xml", e);
}
over here where do i pass the url.
also the response object in the line
response.getEntity() is an object of HttpResponse()?
thank you in advance.
The code you show is the processing after the url connection has been opened, and the result has been obtained. At this point there is no more url to pass.
response is the HttpResponse.
I think you can do something like this:
Url url = new URL("http:// [and so on]");
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(url.openStream()));
Related
I am transitioning to OKHttp and i am using SAXParser in my project. How can i parse the OKHttp response to SAXParser? or how else can I parse XML using the library.
initially this was how I was doing it:
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
SAXParserFactory factory1 = SAXParserFactory.newInstance();
SAXParser parser = factory1.newSAXParser();
FormHandler handler = new FormHandler();
parser.parse(inputStream, handler);
But with OKHTTP, how can i pass Response response = client.newCall(request).execute() to the XML parser?
You might try this :
// 1. get a http response
Response response = client.newCall(request).execute();
// 2. construct a string from the response
String xmlstring = response.body().string();
// 3. construct an InputSource from the string
InputSource inputSource = new InputSource(new StringReader(xmlstring));
// 4. start parsing with SAXParser and handler object
// ( both must have been created before )
parser.parse(inputSource,handler);
PS : in your question you mention XMLPullParser, in your code you're actually using a SAXParser. However, if you have the xml string on your hands, you should do fine with both ways.
I've implemented a SAXparser in my application which has worked fine previously but i'm having problems with a new XML document.
This is my parser
public List<Article> getLatestArticles(String feedUrl) {
URL url = null;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
Log.e("RSS Handler IO", e.getMessage() + " >> " + e.toString());
} catch (SAXException e) {
Log.e("RSS Handler SAX", e.toString());
} catch (ParserConfigurationException e) {
Log.e("RSS Handler Parser Config", e.toString());
}
catch (java.lang.IllegalArgumentException e){
Log.e("RSS Handler lang", e.getMessage() + " >> " + e.toString());
}
return articleList;
}
The parser starts off ok but then i get a java.lang.IllegalArgumentException error. I believe this may be due to an element with no value in my xml feed, it looks like this <Description/>.
Any suggestion on how to fix this would be much appreciated.
If </Description> is a self closing tag (i.e. it has not opening <Description> tag and no text value) then this syntax is perfectly correct.
It is hard to tell exactly what is causing the error without seeing the callback methods (e.g. startElement method) but there is one major gottcha that you can check
The SAX parse method throws an illegalArguementException if the InputStream is null. It might be worth checking the value coming into the SAX parser.
You can use the following code to check the input stream for nulls.
InputStreamReader reader = new InputStreamReader(url.openStream());
if (!reader.ready()) {
System.out.println("error");
}
The connection could close before all the data downloads.
Try using a BufferedInputStream and see if that helps:
BufferedInputStream _url_ = new BufferedInputStream(new URL(feedUrl).openStream());
...
BufferedReader isr = new BufferedReader(new InputStreamReader(_url_));
InputSource is = new InputSource(isr);
xr.parse(is);
<Description/> is the xml construction issue for SAXParser. have a look into the structure.
Ideally it should be </Description> as a closing tag.
For self-closing tags SAXParser will assume it as a closing tag.
So instead of startElement you will get a call from endElement.
I'm using the code to parse RSS from this link IBM - Working with XML on Android...and I have little problem with the URL's. If I use this URL:
static String feedUrl = "http://clarin.feedsportal.com/c/33088/f/577681/index.rss";
It works right, but if I use this URL:
static String feedUrl = "http://www.myworkingdomain.com/api/?m=getFeed&secID=163&lat=0&lng=0&rd=0&d=1";
It gives me:
07-07 19:41:30.134: E/AndroidNews(5454): java.lang.RuntimeException: java.net.MalformedURLException: Protocol not found:
I've already tried hints from other answers...but none of them help me out...
Any other solution?
Thanks for your help!
Seeing your feedUrl, I assume that you want to do an HTTP GET request with parameters. I had a lot of trouble with that too, until I started using a StringBuilder and an HttpClient.
Here's some code, without exception catching:
SAXParserFactory mySAXParserFactory = SAXParserFactory
.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
HttpClient httpClient = new DefaultHttpClient();
StringBuilder uriBuilder = new StringBuilder(
"http://myworkingdomain.com/api/");
uriBuilder.append("?m=getFeed");
uriBuilder.append("&secID=163");
[...]
HttpGet request = new HttpGet(uriBuilder.toString());
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
if (status != HttpStatus.SC_OK) {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
response.getEntity().writeTo(ostream);
Log.e("HTTP CLIENT", ostream.toString());
}
InputStream content = response.getEntity().getContent();
// Process feed
InputSource myInputSource = new InputSource(content);
myInputSource.setEncoding("UTF-8");
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
content.close();
Hope this helps!
Can anybody tell me how to parse HTML content as XML using TagSoup within Android? I am looking for functional code examples if possible.
XMLReader xmlReader = XMLReaderFactory.createXMLReader ("org.ccil.cowan.tagsoup.Parser");
ContentHandler handler = new DefaultHandler () {
public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException
{
// ...
}
};
xmlReader.setContentHandler (handler);
xmlReader.parse (new InputSource (input));
Below is code which should provide you with a means of parsing the web page via the Document produced by TagSoup.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://streak.espn.go.com/en/?date=20120824");
HttpResponse response = client.execute(request);
// Check if server response is valid
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
throw new IOException("Invalid response from server: " + status.toString());
}
// Pull content stream from response
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
try
{
XMLReader parser = XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser");
// Use the TagSoup parser to build an XOM document from HTML
Document doc = new Builder(parser).build(builder.toString());
// Parse the document as needed
Node node = doc.query("...");
}
catch(IOException e)
{ ... }
I am getting this error while trying to Parse the Xml response from the Web Service by SAX Parser in Android.
ERROR in LogCat :- " Response =====> org.xml.sax.InputSource#43b8e230 "
I got to know that I need to convert the response in String may be by toString() Method, but the problem is I don't know how to do that as I had tried all the possible ways I knew for conversion but nothing happened.
In InputSource I am passing the url:-
URL url = new URL("http://www.google.com/ig/api?weather=Ahmedabad");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xmlr = sp.getXMLReader();
DemoHandler myDemoHandler = new DemoHandler();
xmlr.setContentHandler(myDemoHandler);
xmlr.parse(new InputSource(url.openStream()));
Log.e(TAG, "Condition");
System.out.println("Response ====> " + new InputSource(url.openStream().toString()));
ParsedDemoData parsedDemoData = myDemoHandler.getParsedData();
Everything is fine but the response I am getting needs to be converted into String which I don't know how to do.
Can anyone please help in this.
Thanks,
david
To parse an InputStream you don't have to convert it into a string you can directly read its elements and attributes using Parsers available on Android. You can refer the following links to do the same
http://www.ibm.com/developerworks/opensource/library/x-android/index.html
http://www.anddev.org/parsing_xml_from_the_net_-_using_the_saxparser-t353.html
How ever if you are looking for a code that converts Input Stream to string something like this will work
public String convertStreamToString(InputStream is) throws IOException {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
And this should print the stream for you
System.out.println("Response ====> " + convertStreamToString(url.openStream()));