HttpURLConnection.getInputStream() gives UnknownLengthHttpInputStream and due to this Document parsing throws SAX parser exception.
Following is the code
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();
}
Any one knows the reason for UnknownLengthHttpInputStream. I'm getting this error only in android and this code works perfectly in Java Project.
Following is the exception from 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)
Thanks in advance.
UnknownLengthHttpInputStream
stream because your server isn't supplying aContent-Length
or using chunked transfer encoding. When the server does not supply either it must signal the end of the HTTP body by closing the connection - which it appears to do mid-document in this case. Do you have any possibility to sniff the web server traffic when performing this call (e.g. using WireShark)? – LockmanUnknownLengthHttpInputStream
is just a subclass ofAbstractHttpInputStream
etc. etc. - i.e. it's just as much a stream as any other. The issue here is that your server isn't sending aContent-Length
or a valid transfer encoding - which is why libcore is giving you this specific impl. ofInputStream
. If you want to print the contents of the stream you should read it yourself, e.g. like this:ByteArrayOutputStream o = new ByteArrayOutputStream(); int c; byte[] b = new byte[1024]; while ((c = xml.read(b))!=-1){o.write(b,0,c);} System.out.println(b.toString("UTF-8");
– Lockman