SAX Parser不从HttpsURLConection.getInputStream()读取流

时间:2011-06-23 00:41:38

标签: android xml https sax httpurlconnection

我的Android学习进度中又是一个很小的障碍。

这是我的代码:

            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-Length = " + con.getContentLength());

我的响应代码= 200,内容长度= 2593,所以我知道我可以访问该文件

            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));

文件格式正确,我将其复制到本地非安全的http服务器,它运行良好。

可悲的是,当我尝试从安全的http做同样的事情时,它将无法正常工作。

另外,由于我的非安全http成功尝试,我使用HttpClient获取流而不是此方法。

但是,我尝试使用带有安全http的HttpClient失败了。

我更喜欢保留这种方法,如果你知道从我使用SAX的“con”中提取流的任何方法请告诉我!在得到任何帮助之前,先谢谢你。

3 个答案:

答案 0 :(得分:0)

经过反复试验后,我发现了一个解决这个问题的肮脏方法

我删除了数据输出流,然后数据输入流工作正常

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

答案 1 :(得分:0)

使用以下代码

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;
    }

答案 2 :(得分:0)

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());
        }

这里有可用的竞争代码看看Android XML Parsing Tutorial - Using SAXParser

快乐编码:) :):Pragna