我将android应用程序连接到webservice。代码如下:打印到控制台flag1,检索信息,打印到控制台标志2.当程序停止时,打印flag1并且检索的信息不到一半。在logcat中,错误是“DEBUG / SntpClient(78):请求时间失败:java.net.SocketException:协议不支持的地址族”,并且不打印第二个标志。 有什么问题,这是代码:
System.out.println("flag1");
BufferedInputStream bis = new BufferedInputStream(is);
while (bis.available() > 0) {
System.out.print((char)bis.read());
}
System.out.println("flag2");
添加了: logcat输出:
10-06 20:55:15.585: INFO/System.out(460): flag1
10-06 20:55:33.136: DEBUG/SntpClient(78): request time failed: java.net.SocketException: Address family not supported by protocol
10-06 21:00:33.146: DEBUG/SntpClient(78): request time failed: java.net.SocketException: Address family not supported by protocol
10-06 21:03:22.656: DEBUG/AndroidRuntime(473): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
10-06 21:03:22.656: DEBUG/AndroidRuntime(473): CheckJNI is ON
10-06 21:03:23.206: DEBUG/AndroidRuntime(473): Calling main entry com.android.commands.pm.Pm
10-06 21:03:23.326: DEBUG/dalvikvm(275): GC_EXPLICIT freed 10K, 5% free 6302K/6595K, paused 5ms+3ms
连接创建为:
URL url = new URI(address).toURL();
InputStream is = url.openStream();
编辑: 当我想从输入流中读取时不是逐字节而是使用缓冲区:
byte[] buffer = new byte[1024];
int n = 0;
System.out.println("flag1");
while ((n = is.read(buffer)) != -1)
System.out.write(buffer, 0, n);
System.out.println("flag2");
它打印flag1,输入流的一半,然后既不抛出异常也不打印flag2:
10-06 21:26:09.016: INFO/System.out(804): flag1
10-06 21:26:09.356: INFO/System.out(804): less than half of the inputstream
10-06 21:26:17.846: DEBUG/dalvikvm(195): GC_EXPLICIT freed 163K, 5% free 6829K/7175K, paused 9ms+3ms