【问题标题】:SAX Parser Doesn't Read Stream from HttpsURLConection.getInputStream()SAX 解析器不从 HttpsURLConection.getInputStream() 读取流
【发布时间】:2011-06-23 00:41:38
【问题描述】:

在我的 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,请告诉我!!!提前感谢我得到的任何帮助。

【问题讨论】:

  • 失败是什么意思?您能否包括您获得的异常或您看到的错误?内容长度是否返回 0?
  • 您尝试使用 https 的结果如何?异常、不同的状态码、来自服务器的格式错误的输出?
  • 嗨,我没有得到任何异常。它只是没有像文件长度为 0 那样做任何事情

标签: android xml https sax httpurlconnection


【解决方案1】:

经过反复试验,我找到了解决这个问题的方法

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

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

【讨论】:

    【解决方案2】:
    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

    【讨论】:

      【解决方案3】:

      使用以下代码,

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-09
        • 1970-01-01
        • 2014-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多