views:

86

answers:

1

I am creating an Android application that connects to the Fogbugz XML API (sends a request to the API, receives back an XML file). Right now, I am creating a service that will handle these requests, and parse each in order to access usable information. What would be the best way to do this? If I am getting an inputStream, should I use the SAX parser?

        DefaultHttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet("My URL THAT RETURNS AN XML FILE"); 
    HttpResponse response;
    try {
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity(); 
            InputStream stream =  entity.getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream)); 
            String responseString = "";
            String temp;

            while ((temp=bufferedReader.readLine()) != null)
            {
                responseString += temp;
            }

            if (entity != null) { 
                entity.consumeContent(); 
            }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
+2  A: 

I suggest that you use some XML DOM library like XOM or Dom4j. It will be much easier for you to work with tree structure than with SAX events. Personally, I use XOM in Foglyn -- FogBugz for Eclipse plugin. You can pass InputStream directly to your SAX/XOM/Dom4j parser, there is no need to build string first. Furthermore, make sure you use correct encoding ... your code is broken in this regard. (When you pass InputStream to your parser, this is handled by parser. In XOM you can use new Builder().build(InputStream) method).

One FogBugz API hint ... when getting details about case, and you don't need events (comments), don't fetch them at all. I.e. don't put events into list of columns.

Peter Štibraný
Thanks for the info! The string was just to test if my Http request was working, but what do you mean by my code is broken? I have little experience with XML/parsing, and don't really understand what you mean.
mbauer14
@mbauer14: Problem is that you create `new InputStreamReader(stream)` without specifying character encoding -- this will use so-called "default" encoding -- I have no idea what that will be on Android. XML documents have their encoding specified in XML declaration (i.e. `<?xml version="1.0" encoding="utf-8" ?>`), and XML parsers know how to read it, so instead of converting InputStream to Reader yourself, you should pass InputStream to your XML parser directly. (Btw, FogBugz documentations says it always uses UTF-8 when sending output for its XML API)
Peter Štibraný
Ok, that makes sense. Thanks
mbauer14