I’m trying to fetch some XML and eventually use it as a String. Here’s my two methods, the former of which calls the latter.
public static void getAllXML(String url) throws XmlPullParserException, IOException, URISyntaxException{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new InputStreamReader(getUrlData(url)));
XmlUtils.beginDocument(parser,"results");
int eventType = parser.getEventType();
do{
XmlUtils.nextElement(parser);
parser.next();
eventType = parser.getEventType();
if(eventType == XmlPullParser.TEXT){
Log.d("test",parser.getText());
}
} while (eventType != XmlPullParser.END_DOCUMENT) ;
}
public static InputStream getUrlData(String url) throws URISyntaxException, ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI(url));
HttpResponse res = client.execute(method);
return res.getEntity().getContent();
}
Then I use a method which takes an InputStream and converts it to a String. But how do I grab hold of the InputStream returned by the getUrlData method so I can call convertStreamToString(myInputStream)?
You can use a
TeeInputStream( http://commons.apache.org/io/api-1.4/org/apache/commons/io/input/TeeInputStream.html ) to get the input stream that you pass to a parser and also write the input to a ByteArrayInputStream that you can then use withByteArrayOutputStream.toString(String encoding).Something like
Alternatively, you can read the string in first, and then use a
StringReaderwithparser.setInput. If your parser is set up to reject large inputs, or can take anInputStreamas input and does charset detection that you might want to use later, then the approach above is more flexible.