异常信息是这样的:
org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 501: not well-formed (invalid token)
我是调用一个webService原来解析返回的XML字符串,结果遇到了上面的异常。下面是调用webService的核心代码:
Runnable runnable = new Runnable() { @Override public void run() { HttpURLConnection conn = null; InputStream inputStream = null; try { URL url = new URL(baseUrl); conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(8000); conn.setDoInput(true); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "text/html"); conn.setRequestProperty("Accept-Charset", "utf-8"); conn.setRequestProperty("contentType", "utf-8"); inputStream = conn.getInputStream(); byte[] buffer = null; if(conn.getResponseCode() == 200){ buffer = new byte[1024]; ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = inputStream.read(buffer)) != -1) { out.write(buffer, 0, len); } buffer = out.toByteArray(); } mCallback.HandleAsync(buffer); SendMsg("value",buffer); } catch (Exception e) { e.printStackTrace(); Log.e("sjr","Network-error"); } finally{ try { if(inputStream != null){ inputStream.close(); } if(conn != null){ conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); Log.e("sjr","InvokeWebServiceHelper类中释放资源出错"); } } } };
原来是用了InputStreamReader直接一次读完,也没有用conn.getResponseCode() == 200,结果总是出现在这样的异常。现在改成这种循环的方式读从服务端返回的数据。这样就解决了这个问题。因为自己不是搞java的,属于半路出家型的。但从.net方面考虑的话,我想可能是当我用InputStreamReader读这些流的时候,服务端还没有完全将这些流写回客户端,网络一旦出现不稳定就会出现在上面的异常。从这方面想,这个getResponseCode()判断相当的有用。