SAX 解析器不从 HttpsURLConection.getInputStream() 读取流

发布于 2024-11-16 21:20:36 字数 1927 浏览 2 评论 0原文

我的 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 来获取流,而不是此方法。

然而,我尝试将 HttpClient 与安全 http 结合使用却惨遭失败。

我更愿意保留这个方法,如果你知道有什么方法可以从我的“con”中提取与 SAX 一起使用的流,请告诉我!提前感谢我得到的任何帮助。

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-Length = " + 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

是伱的 2024-11-23 21:20:36

经过反复试验,我发现了这个问题的肮脏修复,

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

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

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();
咿呀咿呀哟 2024-11-23 21:20:36
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 解析教程 - 使用 SAXParser

快乐编码:): ) :普拉格纳

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

请远离我 2024-11-23 21:20:36

使用以下代码,

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

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;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文