0

I have code that I would like to convert so that I am grabbing my xml from the server in GZIP format. I am not sure how I would send my requests to see if encoding is accepted and what not. Here is some code:

    public void parse(String locCode, int isMetric, String langId) throws IOException, ParserConfigurationException, SAXException {
    //set member variables
    this.locCode    = locCode;
    this.isMetric   = isMetric;
    this.langId     = langId;
    wdm.metric      = isMetric;

    try {
        mCounter++;
        //create input stream from url
        InputStream is = getInputStream(this.locCode, this.isMetric, this.langId);  
        InputSource inputSource = new InputSource(is);

        inputSource.setEncoding(ENCODING_TYPE);

        //create sax parser and xml reader
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        mCounter = 0;
        //pass in instance of FeedParser
        xr.setContentHandler(new WeatherFeedParser());
        xr.parse(inputSource);
        is.close();
    } catch (SocketException e){
        if (mCounter < 3){
            parse(locCode, isMetric, langId);
        }
        else e.printStackTrace();
    } catch (UnknownHostException e){
        if (mCounter < 3){
            parse(locCode, isMetric, langId);
        }
        else e.printStackTrace();
    }

}

private static final InputStream getInputStream(String locCode, int isMetric, String langId) throws IOException {
    //build url
    String addr = FEED_URL + LOCATION + cleanupInput(locCode) + "&" + METRIC + isMetric + "&" + LANG_ID + langId;
    URL url = new URL(addr);

    //create connection
    mCon = url.openConnection();
    mCon.setConnectTimeout((int)ACCUWX.Time._15_SECONDS);
    mCon.setReadTimeout((int)ACCUWX.Time._15_SECONDS);
    mCon.connect();

    return mCon.getInputStream();        
}

I have read other posts and am not sure where I would implement suggestions with this coding:

HttpUriRequest request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
// ...
httpClient.execute(request);
Check response for content encoding:
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
    instream = new GZIPInputStream(instream);
}
taraloca
  • 9,077
  • 9
  • 44
  • 77
  • Check out http://stackoverflow.com/questions/7139268/automatically-handling-gzip-http-responses-in-android for an alternative implementation of your second code sample using a `GzipDecompressingEntity`. – Twilite Nov 08 '12 at 12:01

1 Answers1

0

Your second code listing would replace much of the body of your getInputStream() method in your first listing.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491