获取未知长度HttpInputStream,同时从Android中的HttpURLConnection获取InputStream

HttpURLConnection.getInputStream() 给出了 UnknownLengthHttpInputStream,并且由于此文档解析会引发 SAX 解析器异常。

以下是代码

try{
    URL url = new URL(uri);
    HttpURLConnection connection =
    (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/xml");

    InputStream xml = connection.getInputStream();
    System.out.println(connection.getResponseCode());
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(connection.getInputStream());
    doc.getDocumentElement().normalize();

}catch(Exception e){
    e.printStackTrace();
}

任何人都知道UnknownLengthHttpInputStream的原因。我只在Android中收到此错误,此代码在Java项目中完美运行。

以下是 LogCat 的例外情况:

08-08 11:07:40.490: W/System.err(1493): org.xml.sax.SAXParseException: Unexpected end of document
08-08 11:07:40.504: W/System.err(1493): at org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:129)
08-08 11:07:40.510: W/System.err(1493): at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:107)
08-08 11:07:40.510: W/System.err(1493): at com.example.testws.MainActivity.onCreate(MainActivity.java:59)
08-08 11:07:40.520: W/System.err(1493): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-08 11:07:40.520: W/System.err(1493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-08 11:07:40.520: W/System.err(1493): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-08 11:07:40.520: W/System.err(1493): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-08 11:07:40.530: W/System.err(1493): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)

提前致谢。


答案 1

它可能是 Http 1.0(旧服务器或配置错误)服务器,或者没有保持活动状态的配置。在这种情况下,在从服务器关闭连接时,流的长度是已知的。尝试在请求标头中指定 http1.1 并保持活动状态(一些谷歌搜索会有所帮助)。只有在服务器响应中指定了内容长度属性,您才会提前知道流长度。

解决办法:将 http 流完全读入 (直到返回 )。然后将 ByteBufferInputStream 扔到你的库中(长度现在已知)ByteBufferStreamread()-1


答案 2

你有没有试过使用apache库来实现这一点?我建议如下:

try {
        HttpClient client = new DefaultHttpClient();  
        String getURL = "http://www.google.com";
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get);  
        HttpEntity resEntityGet = responseGet.getEntity();  
        if (resEntityGet != null) {  
                    //do something with the response
                    Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
                }
} catch (Exception e) {
    e.printStackTrace();
}

然后获取本身的流。Smth like:HttpEntity

InputStream st = entity.getContent();

更多例子在这里: http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/


推荐