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.
Related
I'm using a WEB service which return XML format but with < and > instead of "<" and ">".
Now I dont know how to parse it?
I tried the standard SAX parser:
if (entity != null && responseCode==200) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
BufferedReader rd = null;
rd = new BufferedReader(new InputStreamReader(instream));
InputSource is=new InputSource(rd);
WebServiceRespondParser parser=new WebServiceRespondParser(category);
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser sp=factory.newSAXParser();
XMLReader reader=sp.getXMLReader();
reader.setContentHandler(parser);
reader.parse(is);
markers=parser.getMarkers();
}
WEB service:
http://gisn.tel-aviv.gov.il/ws_iriya_zmina/wsgis.asmx/GetData4TargetLayersFromAddress?Format=xml&TargetIriaLayerIDs=659&Radiuses=2000&Rechov=798&Bayit=3&Knisa=
I read few similar question, but most are in different languages, or doesn't have answer.
That XML is encoded because it's inside the tag. What you need to do is to first parse the original XML, then get the value from the tag. This will get you the proper XML that you can now parse as usual.
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)
{ ... }
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()));
I want to parse the result of a specific URL using Simple Ajax for XML. This is basically my Code:
URL link = new URL(url); // url is just a string representing the url
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(myHandler); // the class of myHandler extends from DefaultHandler
InputStream stream = link.openStream();
InputSource inputSource = new InputSource(stream);
inputSource.setEncoding("ISO-8859-1");
xr.parse(inputSource);
But how can I add a cookie? I know I can add Cookies to HttpClients like so:
BasicClientCookie cookie = new BasicClientCookie("access_token", accessToken);
mHttpClient.getCookieStore().addCookie(cookie);
HttpGet request = new HttpGet("www.reeple.net/xml/login/" + uid);
mHttpClient.execute(request);
But how can I add a cookie to a request, that is handlet by the SAX-Api?
Step #1: Use HttpClient to retrieve the XML as a string, using whatever cookies you want
Step #2: Use SAX to parse the string retrieved by HttpClient