开发者

SAX Parser Doesn't Read Stream from HttpsURLConection.getInputStream()

yet another tiny roadblock in my Android learning progress.

here's my code:

            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

            byte[] encodedPassword = (user + ":" + pass).getBytes();
            String auth = "Basic " + Base64.encodeToString(encodedPassword, false);
            con.setRequestProperty("Authorization", auth);

            con.setRequestMethod("GET");
            con.setRequestProperty("Content-Type","text/xml");
            con.setRequestProperty("Content-Length","" + Integer.toString(urlParameters.getBytes().length));
            con.setRequestProperty("Content-Language", "en-US");
            con.setRequestProperty("Connection", "close");
            con.setUseCaches(false);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setAllowUserInteraction(true);

            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
            int statusCode = ((HttpURLConnection) con).getResponseCode();

            Log.d(TAG, "Response Code = " + statusCode + " Content-Lengt开发者_如何转开发h = " + con.getContentLength());

I got a response code = 200 and content length = 2593 so i know i have access to the file

            DataInputStream re = new DataInputStream(con.getInputStream());

            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            XMLmyHandler myHandler = new XMLmyHandler();
            xr.setContentHandler(myHandler);

            xr.parse(new InputSource(re));

the file is well formatted, i copied it to a local non secure http server and it worked perfectly.

Sadly, when i try to do the same from secure http it wouldn't work.

also, with my non-secure http successful attempts i use HttpClient to get a stream and not this method.

however, my attempts of using HttpClient with secure http failed miserably.

I'd prefer to keep this method, if you know any way to extract a stream from my "con" that works with SAX please let me know!!! thanks ahead on any help i get.


after trial and error i found a dirty fix for this problem

i removed the data output stream then the data input stream worked fine

        //DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        //wr.writeBytes(urlParameters);
        //wr.flush();
        //wr.close();


try {
            StringBuffer inLine = new StringBuffer();
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            MyXMLHandler myExampleHandler = new MyXMLHandler();
            xr.setContentHandler(myExampleHandler);
            InputStream in = this.getResources().openRawResource(
                    R.raw.myxmlfile);
            xr.parse(new InputSource(in));
            MyXMLHandler parsedExampleDataSet = myExampleHandler;
            inLine.append(parsedExampleDataSet.toString());
            in.close();
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
            Log.i(TAG, e.toString());
        }

here is compete code available have a look Android XML Parsing Tutorial - Using SAXParser

Happy coding :):) :Pragna


Use following code,

SAXParserFactory spf = SAXParserFactory.newInstance();
  SAXParser sp = spf.newSAXParser();
  XMLReader xr = sp.getXMLReader();
  XMLmyHandler myHandler = new XMLmyHandler();
   xr.setContentHandler(myHandler);

            xr.parse(getInInputStreamFromURL(ur url here.....));


 public  AndroidHttpClient getClient(String userAgent) {
        HttpParams params = new BasicHttpParams();

        // Turn off stale checking. Our connections break all the time anyway,
        // and it's not worth it to pay the penalty of checking every time.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);

        // Default connection and socket timeout of 20 seconds. Tweak to taste.
        HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
        HttpConnectionParams.setSoTimeout(params, 20 * 1000);
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        // Don't handle redirects -- return them to the caller. Our code
        // often wants to re-POST after a redirect, which we must do ourselves.
        HttpClientParams.setRedirecting(params, false);

        // Set the specified user agent and register standard protocols.
        HttpProtocolParams.setUserAgent(params, userAgent);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        schemeRegistry.register(new Scheme("https", socketFactory, 443));
        ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

        // We use a factory method to modify superclass initialization
        // parameters without the funny call-a-static-method dance.
        return new AndroidHttpClient(manager, params);
    }


 public InputStream getInInputStreamFromURL(String url) {
        InputStream inputStream = null;
        AndroidHttpClient httpClient = null;
        try {
            httpClient = getClient("Ramindu");
            // Example send http request
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            inputStream = response.getEntity().getContent();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "CAUGHT EXCEPTION : " + e);

        }
        return inputStream;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜